如何在ORDER BY中使用CASE函数?

时间:2016-01-12 03:21:10

标签: mysql sql-order-by

我的朋友几次问过question。还有一个答案,这是好的,但不是我的情况。该解决方案的想法是将当前表连接到自身。这对我来说似乎很昂贵且无效,因为实际上我的这些表格中有join votesfavoritescommentsviewed查询。

现在我想知道,我怎么能用CASE函数做到这一点?像这样:

... ORDER BY Type, CASE WHEN AcceptedAnswerId = Id THEN 1 ELSE 0, timestamp

或者有更好的解决方案吗?

为了更具可读性,我将这些示例粘贴到此处:

我有一张这样的表:

// 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         |
+----+--------------------+------+------------------+-----------+

现在我想要这个结果:(请关注订单)

+----+--------------------+------+------------------+-----------+
| 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

2 个答案:

答案 0 :(得分:1)

CASE可行,但您错过了END。但在这种情况下,您也可以使用IF(AcceptedAnswerId = Id,1,0)

在您展示的简单案例中,可以执行:

order by type,if(type=0,(@accepted:=acceptedanswerid),id<>@accepted),timestamp

但我不知道这是否适用于您的实际情况。

答案 1 :(得分:0)

给定表定义(没有适当的索引)+样本数据

CREATE TABLE Table1
    (`Id` int, `QuestionOrAnswer` varchar(9), `Type` int, `AcceptedAnswerId` varchar(4), `related` int NOT NULL, `timestamp` int)
;

INSERT INTO Table1
    (`Id`, `QuestionOrAnswer`, `Type`, `AcceptedAnswerId`, `related`, `timestamp`)
VALUES
    (1, 'question1', 0, '3', 1, 1),
    (2, 'answer1', 1, NULL, 1, 2),
    (3, 'answer2', 1, NULL, 1, 3),
    (4, 'answer3', 1, NULL, 1, 4)

您可以使用查询

SELECT
  t2.*
FROM
  table1 as t1
JOIN
  table1 as t2
 ON
   t1.related=t2.related
 WHERE
   t1.related = 1
   AND t1.Type = 0
 ORDER BY
   t2.Type desc, t2.Id=t1.AcceptedAnswerId, t2.Id

获取特定问题的问题/答案集(t1.related = 1&lt; - 针对其他问题调整该参数。)
不,使用正确的索引,这个查询并不昂贵&#34;。

示例http://sqlfiddle.com/#!9/24954/4(是的,我尝试了4次尝试,grrrrr)