4

我正在尝试从 2 个表帖子和 postmeta 中排序数据

示例 wp_posts 表

ID      post_title          post_name
328   Test Event Five   test-event-five
326   Test Event Four   test-event-four
324   Test Event Three  test-event-three 
321   Test Event  Two   test-event-two 
320   Test Event One    test-event-one

示例 wp_postmeta 表

id  post_id       meta_key                    meta_value
1    328      calendar_start-date            August 08, 2012
2    326      calendar_start-date            August 09, 2012
3    324      calendar_start-date            September 06, 2012
4    321      calendar_start-date            August 23, 2012  
5    320      calendar_start-date            September 17, 2012

为了输出元值中按日期排序的数据,我使用了查询

SELECT wp_posts.ID, 
       wp_posts.post_title, 
       wp_posts.post_name, 
       wp_postmeta.post_id,
       wp_postmeta.meta_value as event_date 
FROM wp_posts, wp_postmeta 
WHERE wp_posts.ID = wp_postmeta.post_id 
AND wp_postmeta.meta_key = 'calendar_start-date' 
AND wp_posts.post_status = 'publish' 
AND wp_posts.post_type = 'calendar' 
ORDER BY DATE_FORMAT( event_date, '%M %d, %Y' ) DESC 
LIMIT 0 , 30

但是结果不是按日期排序的,而是按日期排序的

ID     post_title          post_name      post_id   event_date
328  Test Event Five    test-event-five     328     August 08, 2012
326  Test Event Four    test-event-four     326     August 09, 2012
324  Test Event Three   test-event-three    324     September 06, 2012
321  Test Event  Two    test-event-two      321     August 23, 2012
320  Test Event One     test-event-one      320     September 17, 2012

我在查询中哪里出错了,如何显示按 event_date 正确排序的记录。日期的输入格式为 MM dd, yy 通过 UI/Datepicker。

4

2 回答 2

9

该函数DATE_FORMAT将日期格式化为字符串。但是你想做相反的事情。为此,请使用以下功能STR_TO_DATE

ORDER BY STR_TO_DATE(event_date, '%M %d, %Y') DESC

有关MySQL 中日期函数的更多详细信息,请参阅http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date 。

于 2012-08-18T11:23:29.753 回答
5

DATE_FORMAT从 DATETIME 数据类型到字符串。失败时它不会抱怨,它只是返回 NULL。这就是您的查询有效的原因,即使 ORDER BY 不是。

你需要使用STR_TO_DATE你想要做的事情。

于 2012-08-18T11:23:40.397 回答