使用WHERE IN查找并显示重复值以比较两个值

时间:2013-04-19 20:18:23

标签: mysql count duplicates having where-in

我有一个MYSQL数据库,我希望根据列中的两个值比较重复值。例如

数据库

field_one | field_two | field_three 
------------------------------------
aaa       | 123       | no1
bbb       | 456       | no1
aaa       | 123       | no2
ccc       | 456       | no3 
aaa       | 123       | no3

我想返回这些结果

field_one | field_two | field_three 
------------------------------------
aaa       | 123       | no1
aaa       | 123       | no2

以下是我一直在使用的query,但我不确定如何获得我想要的结果。当我在query中运行phpMyAdmin时,我的浏览器就会卡住。我的数据库也很大。

SELECT * FROM table_name WHERE field_three IN (SELECT field_one, field_two FROM table_name WHERE field_three IN ('no1', 'no2') HAVING COUNT(*) > 1)

由于


已解决

我刚刚从table_name更改了field_three @Gordon Linoff。

field_one

1 个答案:

答案 0 :(得分:0)

我想你想要这个:

select t.*
from t join
     (select field_one, field_two
      from t
      group by field_one, field_two
      having count(*) = 2   -- or do you mean >= 2?
     ) tsum
     on t.field_one = tsum.field_one and t.field_two = tsum.field_two

子查询根据前两列查找重复项。外部查询返回原始行。

如果您想要相对于另一个值的重复项,请将该条件添加到子查询中:

select t.*
from t join
     (select field_one, field_two
      from t
      where field3 = 'no1' -- or whatever you want to set it to
      group by field_one, field_two
      having count(*) = 2   -- or do you mean >= 2?
     ) tsum
     on t.field_one = tsum.field_one and t.field_two = tsum.field_two