MYSQL ORDER BY CASE 问题
2021-11-20 00:00:00
mysql
我有一个这样的数据库:
I have a database like this:
-------------------------------------------------------------------
| id_one | id_two | timestamp_one | timestamp_two |
-------------------------------------------------------------------
| 27 | 35 | 9:30 | NULL |
-------------------------------------------------------------------
| 35 | 27 | NULL | 9:35 |
-------------------------------------------------------------------
| 27 | 35 | 9:34 | NULL |
-------------------------------------------------------------------
| 35 | 27 | NULL | 9:33 |
-------------------------------------------------------------------
我需要拉所有 4 行
ORDER BY 'timestamp_one' if 'id_one'=27 or
ORDER BY 'timestamp_two' if 'id_one'=27
这是我现在的声明:
SELECT * FROM tablename
WHERE id_one=27 OR id_two=27
ORDER BY
CASE WHEN id_one=27 THEN timestamp_one END DESC,
CASE WHEN id_two=27 THEN timestamp_two END DESC
这很有效,因为输出如下:
This works good in that is outputs this:
-------------------------------------------------------------------
| id_one | id_two | timestamp_one | timestamp_two |
-------------------------------------------------------------------
| 27 | 35 | 9:30 | NULL |
-------------------------------------------------------------------
| 27 | 35 | 9:34 | NULL |
-------------------------------------------------------------------
| 35 | 27 | NULL | 9:33 |
-------------------------------------------------------------------
| 35 | 27 | NULL | 9:35 |
-------------------------------------------------------------------
但我需要两个时间戳列来排序,就像它们是一列一样,所以它会这样排序:
But I need to two timestamp columns to order like they are one so it would order like this:
-------------------------------------------------------------------
| id_one | id_two | timestamp_one | timestamp_two |
-------------------------------------------------------------------
| 27 | 35 | 9:30 | NULL |
-------------------------------------------------------------------
| 35 | 27 | NULL | 9:33 |
-------------------------------------------------------------------
| 27 | 35 | 9:34 | NULL |
-------------------------------------------------------------------
| 35 | 27 | NULL | 9:35 |
-------------------------------------------------------------------
我希望这是有道理的.本质上,我试图有两个特定于 WHERE 条件的 ORDER BY 列.然后,一旦为该行选择了正确的 ORDER BY 列,它就会按整个时间戳对 ROWS 进行排序.
I hope this makes sense. Essentially, I am trying to have two ORDER BY columns that are specific to a WHERE condition. Then once the correct ORDER BY column is chosen for that row, it orders the ROWS by the timestamp as a whole.
推荐答案
SELECT id_one, id_two, timestamp_one, timestamp_two
FROM tablename
WHERE id_one = 27
OR id_two = 27
ORDER BY
CASE
WHEN id_one=27 THEN timestamp_one
WHEN id_two=27 THEN timestamp_two
END DESC
相关文章