选择具有相同列值的行(Mysql)

时间:2016-02-29 17:54:27

标签: mysql

我得到了以下表格结构。

 id  ||  column a  ||  column b 
---------------------------------
 1         1              2      
 2         5              1
 3         1              2
 4         2              3
 5         6              52
 6         1              1
 7         3              5
 8         6              52
 9         52             6
10         13             88

如何在两列中选择具有相同值的行?所以在我的情况下,我应该得到id等于1,3,5,8

的行

2 个答案:

答案 0 :(得分:2)

请你试试:

Select t1.id, t1.ColumnA, t1.ColumnB
From Table t1 
inner join Table t2 on (t1.id <> i2.id AND t1.columnA = t2.columnA AND t1.columnB = t2.columnB)

答案 1 :(得分:2)

您可以使用分组:

SELECT COLUMN_A, COLUMN_B
FROM mytable
GROUP BY COLUMN_A, COLUMN_B
HAVING COUNT(*) > 1

这将选择所有COLUMN_A, COLUMN_B个重复对。要获得整行,您可以使用:

SELECT t1.ID, t1.COLUMN_A, t1.COLUMN_B
FROM mytable AS t1
INNER JOIN (
   SELECT COLUMN_A, COLUMN_B
   FROM mytable
   GROUP BY COLUMN_A, COLUMN_B
   HAVING COUNT(*) > 1
) AS t2 ON t1.COLUMN_A = t2.COLUMN_A AND t1.COLUMN_B = t2.COLUMN_B 

或者,您可以使用EXISTS

SELECT *
FROM mytable AS t1
WHERE EXISTS (
   SELECT 1
   FROM mytable AS t2
   WHERE t1.ID <> t2.ID AND 
         t1.COLUMN_A = t2.COLUMN_A AND 
         t1.COLUMN_B = t2.COLUMN_B)