如何使用MySQL语句选择重复记录并保留数据?

时间:2014-02-17 15:01:16

标签: mysql sql

例如,我的表categories是这样的:

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

有人可以帮助我吗?

2 个答案:

答案 0 :(得分: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

的查询

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