MySQL ORDER BY CASE但保留重复

时间:2014-10-02 18:02:46

标签: mysql sql case sql-order-by

我有一个格式为

的数据库
| Field      | Type             | Null | Key | Default | Extra          |
| word       | varchar(60)      | NO   |     | NULL    |                |
| english_id | int(10) unsigned | NO   | PRI | NULL    | auto_increment |


| word | english_id |
| the  |          1 |
| of   |          2 |
| and  |          3 |
| a    |          4 |
| to   |          5 |
| in   |          6 |
| ant  |          7 |
| be   |          8 |
| that |          9 |
| was  |         10 |

我希望能够按输入的顺序排序,但也要保留重复。因此,如果他们输入"a cat and a dog",我会在下面的SQL查询中获得正确的顺序。问题是因为我使用了a两次,所以第二个a没有出现。如何在输出中按顺序保留重复值?这是当前的查询。

select english_id, word from english where word in ("Here", "are", "are", "dogs")
order by CASE word
  WHEN "here" then 1
  WHEN "are" then 2
  WHEN "are" then 3
  WHEN "dogs" then 4
END;

这是它的输出

| english_id | word |
|        131 | here |
|         26 | are  |
|       1679 | dogs |

我希望它看起来像这样

| english_id | word |
|        131 | here |
|         26 | are  |
|         26 | are  |
|       1679 | dogs |

1 个答案:

答案 0 :(得分:3)

要让are显示两次,您需要加入一个"表"其中are出现两次。你可以这样得到这样的表:

SELECT 'Here'
UNION ALL SELECT 'are'
UNION ALL SELECT 'are'
UNION ALL SELECT 'dogs'

只需将english表加入查询中,即可正常使用:

SELECT english_id, english.word
FROM english
JOIN (
    SELECT 'Here' AS word
    UNION ALL SELECT 'are'
    UNION ALL SELECT 'are'
    UNION ALL SELECT 'dogs') WordsToSearch ON english.word = WordsToSearch.word
ORDER BY CASE word
  WHEN "here" then 1
  WHEN "are" then 2
  WHEN "are" then 3
  WHEN "dogs" then 4
  END;

您还可以在单​​词列表中指定订单信息,以简化查询:

SELECT english_id, english.word
FROM english
JOIN (
    SELECT 'Here' AS word, 1 AS word_order
    UNION ALL SELECT 'are', 2
    UNION ALL SELECT 'are', 3
    UNION ALL SELECT 'dogs', 4) WordsToSearch ON english.word = WordsToSearch.word
ORDER BY WordsToSearch.word_order;

<强>附录

OP遇到了最初发布的查询问题,因为查询第一行中的列word没有别名,并且非常友好地在评论中发布了更新后的查询。上述查询已针对此修复进行了更新。