wpdb COALESCE won't work

时间:2020-11-13 作者:pixelngrain

我正在努力使用COALESCE 来自自定义表。如果第一个结果为null,但wpdb 结果查询字符串本身而不是结果。

$query = "SELECT coalesce(";
$query .= "(SELECT order_number FROM wp_gs_p_cart ";
$query .= "WHERE group_user = %d AND group_id = %d AND identifier = %s ORDER BY id DESC LIMIT 1),";
$query .= "(SELECT order_number FROM wp_gs_p_cart ORDER BY id DESC LIMIT 1)";
$query .= ");";

$prepare = $wpdb->prepare($query, $user_id, $group_id, $identifier);

return $wpdb->get_results($prepare);

// or 

return $wpdb->get_row($prepare);

结果

Array
(
    [0] => stdClass Object
        (
            [coalesce((SELECT order_number FROM wp_gs_p_cart WHERE group_user = 73 AND group_id = 298 AND identifier = \'AtR4deAVgU4Ensi1_1ac2b33a4df7c5f0cf148d6232074352\' ORDER BY id DESC LIMIT 1),(SELECT order_number FROM wp_gs_p_cart ORDER BY id DESC LIMIT 1))] => 3333
        )

)

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

据我所见,查询确实返回了一个结果,但COALESCE() 结果没有命名,因此MySQL和WordPress使用整个COALESCE() 作为字段名查询。

为了避免这种情况,您可以为COALESCE(), e、 g。

//$query = "SELECT COALESCE( <your queries> ) AS <alias>";
$query = "SELECT COALESCE( NULL, 5, 2, 3 ) AS order_number";

$results = $wpdb->get_results( $query );
// Assuming $results[0] exists:
echo $results[0]->order_number;

$result = $wpdb->get_row( $query );
// Assuming the query returned a result:
echo $result->order_number;
但是自从COALESCE() 只返回一个结果,您可以使用get_var():

//$query = "SELECT COALESCE( NULL, 5, 2, 3 )"; // this works
// But maybe, better with an alias.
$query = "SELECT COALESCE( NULL, 5, 2, 3 ) AS order_number";

$result = $wpdb->get_var( $query );
echo $result;

相关推荐

ACF:如何在使用wp_Query的同时发布循环中ACF字段的值?

我正在使用ACF向自定义帖子类型添加字段。我创建了一个WP\\u Query实例来设置循环。在循环中,我可以使用\\u title()和\\u content()发布标准字段。但是,ACF函数the\\u字段不会发布附加字段的值。“the\\u field()”和“echo the\\u field()”都不会生成字段值。所以如何准确发布这些值?这是我的循环:$jobs_query = new WP_Query($args) ; if ($jobs_query->have