我有一个mysql表格 表:订单
Order | day | time
1 | Tuesday 31-10-2017 | 10:00 AM
2 | Thursday 02-11-2017 | 11:00 AM
3 | Tuesday 31-10-2017 | 01:00 PM
4 | Tuesday 31-10-2017 | 10:00 AM
5 | Sunday 29-10-2017 | 09:30 AM
我需要根据日期和时间对订单进行排序,例如:
Order | day | time
5 | Sunday 29-10-2017 | 09:30 AM
1 | Tuesday 31-10-2017 | 10:00 AM
4 | Tuesday 31-10-2017 | 10:30 AM
3 | Tuesday 31-10-2017 | 01:00 PM
2 | Thursday 02-11-2017 | 11:00 AM
尝试:
select * from request ORDER BY STR_TO_DATE(time,'%h:%i%p') asc, STR_TO_DATE(day,'%l %d-%m-%Y') desc
但那没有按预期排序......
答案 0 :(得分:2)
实际上,您应该使用内部日期格式存储日期,而不是字符串。您可以使用日期/时间功能轻松获取一周的日期。
您的日期格式使这更难,但您可以这样做:
order by str_to_date(substring_index(day, ' ', -1), '%d-%m-%Y'),
str_to_date(time,'%h:%i%p')
现在你已经解决了这个问题,请回到你的数据并执行:
alter table orders add column orderdate datetime;
update orders
set orderdate = addtime(str_to_date(substring_index(day, ' ', -1), '%d-%m-%Y'),
str_to_date(time,'%h:%i%p'));
检查orderdate
是否正确。然后做:
alter table orders drop column day;
alter table orders drop column time;
不是很好吗?您的数据现已修复。
答案 1 :(得分:0)
以下查询将起作用:
select * from request
ORDER BY STR_TO_DATE(SUBSTRING_INDEX(day,' ',-1),'%d-%m-%Y'),
STR_TO_DATE(time,'%h:%i%p') desc,
答案 2 :(得分:0)
首先,您应该首先订购更重要的列。所以订单陈述的顺序应该是;
ORDER BY STR_TO_DATE(day,'%l %d-%m-%Y') desc, STR_TO_DATE(time,'%h:%i%p') asc
日期栏应该是asc,而不是desc;
ORDER BY STR_TO_DATE(day,'%l %d-%m-%Y') asc, STR_TO_DATE(time,'%h:%i%p') asc
顺便说一下,我认为一周中的the pattern应该是%W
而不是%l
;
ORDER BY STR_TO_DATE(day,'%W %d-%m-%Y') asc, STR_TO_DATE(time,'%h:%i%p') asc