按日期排序并包含没有日期的记录?

时间:2013-04-27 01:58:24

标签: php mysql datetime

是否可以按日期对记录进行排序,但仍包含没有日期值的记录?后者将放在列表的末尾。

这是一个wordpress查询,但我认为我的问题在这里更合适:

$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 .= " AND CAST( $wpdb->postmeta.meta_value AS DATE )";
$sql .= " GROUP BY $wpdb->posts.ID";
$sql .= " ORDER BY $wpdb->postmeta.meta_value ASC";

如何修改它?

3 个答案:

答案 0 :(得分:1)

这个有用:

$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 $wpdb->posts.ID ASC, CAST( $wpdb->postmeta.meta_value AS DATE ) ASC";

感谢您的帮助!

答案 1 :(得分:1)

只需删除条件WHERE … CAST( $wpdb->postmeta.meta_value AS DATE ),因为这会从结果中删除NULL个日期。如果没有它,将包含行,并且排序不会改变它。然后,您可以在ORDER BY部分中重新插入该表达式,以按日期排序。 NULL值会被排序到开头,即您的比较小于非NULL值。

答案 2 :(得分:0)

尝试SELECT * FROM TABLE ORDER BY date