我正在尝试从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。
答案 0 :(得分:6)
函数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。
答案 1 :(得分:4)
DATE_FORMAT
从DATETIME数据类型转换为字符串。当它失败时它不会发牢骚,它只返回NULL。这就是你的查询工作的原因,即使ORDER BY不是。
您需要使用STR_TO_DATE
来完成您的工作。