2014-10-02 44 views
2

我有一個數據庫的MySQL的ORDER BY CASE但要重複

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

回答

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; 

附錄

由於查詢的第一行中的列word未被別名,因此很容易在查詢中發佈更新的查詢。上述查詢已針對此修復程序進行了更新。

+0

謝謝你的幫助。我很困惑WordToSearch是什麼?我的數據庫被命名爲語言。 – 2014-10-03 16:39:57

+0

'WordsToSearch'是「SELECT ... UNION SELECT ... UNION SELECT」查詢的別名。我起了名字。你可以在這裏使用你想要的任何名字。 – 2014-10-03 19:15:52

+0

非常感謝您的幫助。我剛纔提出這個小小的變化,它的工作SELECT english_id,english.word 從英語 JOIN( SELECT '這裏' AS字,1 AS word_order UNION ALL SELECT '是',2 UNION ALL SELECT '是',3 UNION ALL SELECT'dogs',4)WordsToSearch on english.word = WordsToSearch.word ORDER BY WordsToSearch.word_order; – 2014-10-03 20:15:19