ORDER BY日期ASC在带有日期的记录之前放置没有日期的记录?

时间:2013-08-09 08:17:38

标签: mysql sql wordpress

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. Post Z. Due:8月4日
  6. 为什么总是先返回没有_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. Post Z. Due:8月4日
    4. 发布A。
    5. 发布B.
    6. 思想?

3 个答案:

答案 0 :(得分:4)

"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";

答案 1 :(得分:1)

您可以将函数isnull添加到您的order by子句中:

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

答案 2 :(得分:1)

ORDER BY IFNULL(_due, MAXDATE)

其中MAXDATE是某个未来日期,高于_due值。