从两列中的MySQL表中查找相同的值

时间:2012-07-05 17:03:52

标签: php mysql

我只需要过滤这些在x和y列中具有相同值的表行。

 _______________________________________
|
|    x    |      y     |      name     |
________________________________________
|
|   1     |      2     |     A         |
|______________________________________
|   2     |      1     |      B        |
|______________________________________
|   1     |      2    |     C          | 
|_______________________________________  

最终结果应该是我有A和C的结果。我需要过滤这些具有相同x和y值的行。

 _______________________________________
|
|    x    |      y     |      name     |
________________________________________
|
|   1     |      2     |     A         |
|______________________________________
 ______________________________________
|   1     |      2    |     C          | 
|_______________________________________  

我尝试过这段代码,但我只设法使用一个字段。

select * 
from auto 
where x in (
        select x 
        from auto 
        group by x 
        having count(*) > 1
    );

2 个答案:

答案 0 :(得分:3)

SELECT t1.*
FROM tablename t1, tablename t2
WHERE t1.x = t2.x
AND t1.y = t2.y
AND t1.primary_key != t2.primary_key

答案 1 :(得分:2)

select * from 
auto a, ( SELECT x, y, COUNT(*) FROM auto GROUP BY x, y HAVING COUNT(*) > 1 ) b
where a.x = b.x
and a.y = b.y

会将您的其他问题标记为重复