gpt4 book ai didi

mysql - 如何在mysql中按两列对表进行条件排序?

转载 作者:行者123 更新时间:2023-11-29 23:57:12 24 4
gpt4 key购买 nike

Mysql

mysql> select origin_id, destination_id,travel_date,departure_time,available_seats from `schedules` WHERE  travel_date = '2014-08-12' and origin_id = '134' and destination_id = '251'  ORDER BY STR_TO_DATE(departure_time,'%h:%i%p') limit 10;

+-----------+----------------+-------------+----------------+-----------------+
| origin_id | destination_id | travel_date | departure_time | available_seats |
+-----------+----------------+-------------+----------------+-----------------+
| 134 | 251 | 2014-08-12 | 06:00 AM | 34 |
| 134 | 251 | 2014-08-12 | 07:00 AM | 43 |
| 134 | 251 | 2014-08-12 | 07:30 AM | 0 |
| 134 | 251 | 2014-08-12 | 07:30 AM | 34 |
| 134 | 251 | 2014-08-12 | 08:30 AM | 0 |
| 134 | 251 | 2014-08-12 | 08:30 AM | 29 |
| 134 | 251 | 2014-08-12 | 10:15 AM | 36 |
| 134 | 251 | 2014-08-12 | 10:15 AM | 0 |
| 134 | 251 | 2014-08-12 | 10:30 AM | 29 |
| 134 | 251 | 2014-08-12 | 11:00 AM | 0 |
+-----------+----------------+-------------+----------------+-----------------+
10 rows in set (0.04 sec)

第一个查询:在这个查询中,我按出发时间给出订单。但我想要所有具有 available_seats 0 的记录,这些记录应该仅按出发时间排序在最后。

所需输出... ??

   +-----------+----------------+-------------+----------------+-----------------+
| origin_id | destination_id | travel_date | departure_time | available_seats |
+-----------+----------------+-------------+----------------+-----------------+
| 134 | 251 | 2014-08-12 | 06:00 AM | 34 |
| 134 | 251 | 2014-08-12 | 07:00 AM | 43 |
| 134 | 251 | 2014-08-12 | 07:30 AM | 34 |
| 134 | 251 | 2014-08-12 | 08:30 AM | 29 |
| 134 | 251 | 2014-08-12 | 10:15 AM | 36 |
| 134 | 251 | 2014-08-12 | 10:30 AM | 29 |
| 134 | 251 | 2014-08-12 | 07:30 AM | 0 |
| 134 | 251 | 2014-08-12 | 08:30 AM | 0 |
| 134 | 251 | 2014-08-12 | 10:15 AM | 0 |
| 134 | 251 | 2014-08-12 | 11:00 AM | 0 |
+-----------+----------------+-------------+----------------+-----------------+

是否可以用mysql查询。或者用其他方式???

最佳答案

使用 CASE 子句:

ORDER BY CASE 
WHEN available_seats=0 THEN '99:99'
else STR_TO_DATE(departure_time,'%h:%i%p') END

请注意,您指定了 LIMIT 子句,这可能会产生意外结果。

此外,如果您同时有 AM 和 PM 时间,则按 AM/PM 时间排序将不会按时间顺序排序。

关于mysql - 如何在mysql中按两列对表进行条件排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25257503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com