postmeta"; $sql .= " INNER JOIN $wpdb->posts ON $wpdb->po-6ren">
gpt4 book ai didi

mysql - ORDER BY date ASC 将没有日期的记录放在有日期的记录之前?

转载 作者:行者123 更新时间:2023-11-29 01:22:01 25 4
gpt4 key购买 nike

global $wpdb;

$sql = "SELECT * FROM $wpdb->postmeta";
$sql .= " INNER JOIN $wpdb->posts ON $wpdb->postmeta.post_id = $wpdb->posts.ID";
$sql .= " WHERE $wpdb->posts.post_type = 'task'";
$sql .= " AND $wpdb->posts.post_parent IN ( SELECT `ID` FROM $wpdb->posts WHERE `post_type` = 'task_list' AND `post_parent` IN ( SELECT `ID` FROM $wpdb->posts WHERE `post_status` = 'publish' AND `post_type` = 'project' ) )";
$sql .= " AND $wpdb->postmeta.post_id IN ( SELECT `post_id` FROM $wpdb->postmeta WHERE $wpdb->postmeta.meta_key = '_completed' AND $wpdb->postmeta.meta_value = '0' )";
$sql .= " AND $wpdb->postmeta.post_id IN ( SELECT `post_id` FROM $wpdb->postmeta WHERE $wpdb->postmeta.meta_key = '_assigned' AND $wpdb->postmeta.meta_value = '%s' )";
$sql .= " AND $wpdb->postmeta.meta_key = '_due'";
$sql .= " GROUP BY $wpdb->posts.ID";
$sql .= " ORDER BY CAST( $wpdb->postmeta.meta_value AS DATE ) ASC, $wpdb->posts.ID ASC";

$tasks = $wpdb->get_results( sprintf( $sql, $user_id ) );

return $tasks;

查询结果是这样的:

  1. 发布 A.
  2. 后 B.
  3. 发布 X。截止日期:8 月 2 日
  4. 发布 Y。截止日期:8 月 3 日
  5. Z 后截止日期:8 月 4 日

为什么没有 _due 值的帖子总是先返回?我怎样才能使它们总是最后返回?如果我这样做:

 $sql .= " ORDER BY $wpdb->posts.ID ASC, CAST( $wpdb->postmeta.meta_value AS DATE ) ASC";

没有 _due 值的帖子随机放置在有 _due 值的帖子之间。

理想的结果应该是:

  1. 发布 X。截止日期:8 月 2 日
  2. 发布 Y。截止日期:8 月 3 日
  3. Z 后截止日期:8 月 4 日
  4. 发布 A.
  5. 后 B.

想法?

最佳答案

"ORDER BY CASE WHEN CAST( $wpdb->postmeta.meta_value AS DATE ) '' THEN 1 ELSE 0             
END,CAST( $wpdb->postmeta.meta_value AS DATE )ASC, $wpdb->posts.ID ASC";

关于mysql - ORDER BY date ASC 将没有日期的记录放在有日期的记录之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18142654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com