0

我一直面临着一个我无法摆脱的小困惑。我有一个表“ user_questions ”,其属性为idquestion_sequence_numbertitle。从该表中,我想根据给出的优先级获取记录,例如我首先给出了“ question_sequence_number ”,然后是“ id ”。所以我想要的是记录应该首先显示给定的序列号,然后记录应该显示我给定的ID 。
为此,我编写了一个mySql查询,如下所示:

SELECT "user_questions".* FROM "user_questions" WHERE (question_sequence_number IN (11,13,16,19) OR id IN (198,199,200,201,202))

但是记录首先是我给出的ids和问题序列号的剩余记录。

任何人都可以帮助我实现这一目标吗?

谢谢。

4

2 回答 2

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

输出:

| 身份证 | QUESTION_SEQUENCE_NUMBER |
|-----|--------------|
| 2 | 11 |
| 4 | 13 |
| 3 | 16 |
| 1 | 19 |
| 198 | 5 |
| 199 | 4 |
| 200 | 3 |
| 201 | 2 |
| 202 | 1 |

这是SQLFiddle演示

于 2013-08-31T06:19:08.717 回答
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; 
于 2013-08-31T06:14:35.993 回答