2014-02-17 59 views
0

例如,我的表categories是這樣的:如何選擇重複記錄並使用MySQL語句保存數據?

categories_id     categories_name 
----------------------   -------------------- 
1         aaa    
2         bbb    
3         ccc     
5         ddd    
9         eee 

我用下面的語句使重複記錄。但重複的記錄不會出現。

SELECT categories_id, categories_name 
FROM categories 
WHERE categories_name in ("aaa","bbb","bbb","ccc","ccc","ddd","ddd","ddd") 
ORDER BY categories_name 

我想這樣的記錄:

categories_id     categories_name 
----------------------   -------------------- 
1         aaa    
2         bbb 
2         bbb    
3         ccc 
3         ccc     
5         ddd 
5         ddd    
5         ddd 

有人能幫助我嗎?

+1

我真的不明白你的問題你能更清楚嗎? –

+0

只處理應用程序級別的邏輯 – Strawberry

+1

分類表是否包含重複數據? –

回答

1

以下代碼給出了所需的輸出:

SELECT Tab1.categories_id, Tab1.categories_name 
FROM categories AS Tab1 
RIGHT JOIN 
(
    SELECT "aaa" AS categories_name 
    UNION ALL 
    SELECT "bbb" 
    UNION ALL 
    SELECT "bbb" 
    UNION ALL 
    SELECT "ccc" 
    UNION ALL 
    SELECT "ccc" 
    UNION ALL 
    SELECT "ddd" 
    UNION ALL 
    SELECT "ddd" 
    UNION ALL 
    SELECT "ddd" 
) AS Tab2 
ON Tab1.categories_name = Tab2.categories_name 
ORDER BY Tab1.categories_name; 

SQL Fiddle

+0

謝謝你的回答,我在數據庫中創建一個新的臨時表並獲取記錄。我知道我的應用程序非常奇怪,而且我的英語不好,我不能很好地表達我的想法。 – GiGi

1

我想就不會有任何你想要的查詢來完成的更好的辦法,但對於當前的要求下可能是一個辦法:

SELECT c.id, a.category 
FROM 
    (SELECT 'aaa' AS category 
    UNION ALL 
    SELECT 'aaa' 
    UNION ALL 
    SELECT 'ccc' 
    UNION ALL 
    SELECT 'ccc' 
    UNION ALL 
    SELECT 'eee' 
    UNION ALL 
    SELECT 'bbb' 
    ) a 
LEFT JOIN categories c 
ON c.category = a.category 
ORDER BY id; 

看到查詢的工作:http://www.sqlfiddle.com/#!2/2897d/11