MySQL在表中找到对

时间:2014-06-28 19:59:54

标签: mysql

我的表格看起来像这样

+----+----+----+----+
| id | c1 | c2 | c3 |
+----+----+----+----+
|  1 |  a |  x | 13 |
|  2 |  b |  z | 27 |
|  3 |  c |  y | 24 |
|  4 |  a |  y | 11 |
|  5 |  a |  x | 19 |
|  6 |  b |  y | 22 |
|  7 |  b |  z | 20 |
+----+----+----+----+

我需要查找具有重复(c1, c2)值对的所有行。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

使用WHERE:

SELECT t1.c1, t1.c2, t2.c1, t2.c2
FROM table t1, table t2
WHERE t1.c1 = t2.c1 
AND t1.c2 = t2.c2
AND t1.id != t2.id

使用INNER JOIN

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

说明:

t1和t2指的是同一张表 在表t1中搜索具有相同c1和c2但在t2中具有不同ID的记录。

答案 1 :(得分:1)

select * from your_table
where id not in
(
  select min(id)
  from your_table
  group by c1, c2
  having count(*) = 1
)

答案 2 :(得分:0)

你也可以使用加入

select t.* from t join (
select * from t group by c1,c2 having count(*) >1
) t1 using(c1,c2)

Demo