我一直面临一个小小的困惑,我无法摆脱它。
我有一个表“ user_questions ”,其中包含 id , question_sequence_number ,标题属性。从该表中我想根据优先级给出记录,就像我先给出' question_sequence_number '然后' id '。所以我想要的是记录应该第一次显示我已经给出的序列号,并且记录应该显示 next Ids 我已经给了。
为此,我写了一个 mySql 查询,如下所示:
SELECT "user_questions".* FROM "user_questions" WHERE (question_sequence_number IN (11,13,16,19) OR id IN (198,199,200,201,202))
但是记录首先是 ID ,我已经给出了问题序列号的剩余记录。
有人可以帮我解决这个问题吗?
感谢。
答案 0 :(得分:2)
要获得所需的记录顺序,必须使用ORDER BY
子句。否则订单无法保证。
据说你可以试试这样的事情
SELECT *
FROM user_questions
WHERE question_sequence_number IN (11,13,16,19)
OR id IN (198,199,200,201,202)
ORDER BY (question_sequence_number IN (11,13,16,19)) DESC,
CASE WHEN question_sequence_number IN (11,13,16,19)
THEN question_sequence_number
ELSE id
END
输出:
| ID | QUESTION_SEQUENCE_NUMBER | |-----|--------------------------| | 2 | 11 | | 4 | 13 | | 3 | 16 | | 1 | 19 | | 198 | 5 | | 199 | 4 | | 200 | 3 | | 201 | 2 | | 202 | 1 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
DECLARE _Str VARCHAR(500);
SET _Str=CONCAT("SELECT user_questions.* FROM user_questions WHERE (question_sequence_number IN ("11,13,16,19") OR id IN ("198,199,200,201,202")")
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;