2
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。

想法?

4

3 回答 3

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";
于 2013-08-09T08:27:54.637 回答
1

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

$sql .= " ORDER BY $wpdb->posts.ID ASC, ISNULL($wpdb->postmeta.meta_value),CAST( $wpdb->postmeta.meta_value AS DATE ) ASC";
于 2013-08-09T08:22:08.813 回答
1
ORDER BY IFNULL(_due, MAXDATE)

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

于 2013-08-09T08:25:14.567 回答