How to sort results order by timestamp except one of them?

最后都变了- 提交于 2019-11-28 10:26:32

问题


I have a table like this:

// Mytable
+----+--------------------+------+------------------+-----------+
| Id |  QuestionOrAnswer  | Type | AcceptedAnswerId | timestamp |
+----+--------------------+------+------------------+-----------+
| 1  | question1          | 0    | 3                | 1         |
| 2  | answer1            | 1    | NULL             | 2         |
| 3  | answer2            | 1    | NULL             | 3         | -- accepted answer
| 4  | answer3            | 1    | NULL             | 4         |
+----+--------------------+------+------------------+-----------+

Now I want this result: (please focus on the order)

+----+--------------------+------+------------------+-----------+
| Id |  QuestionOrAnswer  | Type | AcceptedAnswerId | timestamp |
+----+--------------------+------+------------------+-----------+
| 1  | question1          | 0    | 3                | 1         |
| 3  | answer2            | 1    | NULL             | 3         | -- accepted answer 
| 2  | answer1            | 1    | NULL             | 2         |
| 4  | answer3            | 1    | NULL             | 4         |
+----+--------------------+------+------------------+-----------+
//                          ^ 0 means question and 1 means answer

Well how can I do that? (I want something exactly like SO sorting)


Here is my try:

SELECT * FROM Mytable WHERE 1 ORDER BY Type, {I need to add something here}, timestamp

回答1:


You need to join the table to itself to determine which row is the accepted answer. Then the information can be used in the ORDER BY:

SELECT t.*
FROM Mytable t LEFT JOIN
     Mytable tans
     ON t.id = tans.AcceptedAnswerId
ORDER BY t.Type,
         (tans.id IS NOT NULL) DESC,
         t.timestamp


来源:https://stackoverflow.com/questions/34734395/how-to-sort-results-order-by-timestamp-except-one-of-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!