使用SQL获取重复的行

时间:2013-05-20 07:15:14

标签: mysql sql

我正在尝试开发一个查询来获取具有重复值的行,我需要获取两个记录,即重复记录和真实记录,例如

id  keyword
-------------------
1   Apple
2   Orange
3   Apple
4   Grape
5   Banana
6   Grape

查询结果应为:

id  keyword
-------------------
1   Apple
3   Apple
4   Grape
6   Grape

请有人帮助我!

3 个答案:

答案 0 :(得分:2)

查询:

select * from 
table where keyword in
(select keyword 
from table
group by keyword 
having count(keyword)>1)

答案 1 :(得分:0)

这可能会有所帮助:

SELECT t1.id, t1.keyword                                     
FROM table t1              
INNER JOIN table t2                   
ON t1.id != t2.id           
AND t1.keyword=t2.keyword

在SQL Fiddle上测试 http://sqlfiddle.com/#!2/44dbb/1/0

答案 2 :(得分:0)

一种方法:

SELECT * 
FROM `table` t1
WHERE 
    (SELECT COUNT(*) FROM `table` t2 WHERE t2.keyword = t1.keyword) > 1

另一种方式:

SELECT t1.*
FROM `table` t1
JOIN `table` t2 ON t1.keyword = t2.keyword
WHERE t1.id != t2.id