如何找到多列的重复记录?表具有主键(自动增量)
EG
ID a_id b_id
---- ---- ------
1 34 23
2 34 23
3 35 25
例如,我想找到具有相同a_id和b_id ...
的记录由于
答案 0 :(得分:3)
select t.ID, t.a_id, t.b_id
from (
select a_id, b_id
from tbl
group by a_id, b_id
having count(*) > 1) x, tbl t
where x.a_id = t.a_id and x.b_id = t.b_id
order by t.a_id, t.b_id
此查询将显示元组上的所有重复项(a_id,b_id)
答案 1 :(得分:1)
SELECT r1.id, r2.id
FROM test r1, test r2
WHERE r1.id < r2.id
AND r1.a_id = r2.a_id
AND r1.b_id = r2.b_id
答案 2 :(得分:0)
修改强>
误读了你要找的东西。您可以使用group by参数在表中找到重复的条目,如上所述进行选择,甚至是自联接。
mysql> SELECT * FROM my_table;
+------+------+------+
| ID | a_id | b_id |
+------+------+------+
| 1 | 34 | 23 |
| 2 | 34 | 23 |
| 3 | 35 | 25 |
+------+------+------+
3 rows in set (0.00 sec)
mysql> SELECT t1.ID source_row,
-> t2.ID same_as_row,
-> t1.a_id a_id,
-> t1.b_id b_id
-> FROM my_table t1
-> JOIN my_table t2
-> ON t1.a_id = t2.a_id
-> AND t1.b_id = t2.b_id
-> AND t1.ID != t2.ID;
+------------+-------------+------+------+
| source_row | same_as_row | a_id | b_id |
+------------+-------------+------+------+
| 2 | 1 | 34 | 23 |
| 1 | 2 | 34 | 23 |
+------------+-------------+------+------+
2 rows in set (0.00 sec)
<强> EDIT2:强>
mysql> SELECT * FROM my_table;
+------+------+------+
| ID | a_id | b_id |
+------+------+------+
| 1 | 34 | 23 | # same as 2, 4
| 2 | 34 | 23 | # same as 1, 4
| 3 | 35 | 25 |
| 4 | 34 | 23 | # same as 1, 2
| 5 | 31 | 23 |
+------+------+------+
mysql> SELECT t1.ID source_row,
-> t2.ID same_as_row,
-> t1.a_id a_id,
-> t1.b_id b_id
-> FROM my_table t1
-> JOIN my_table t2
-> ON t1.a_id = t2.a_id
-> AND t1.b_id = t2.b_id
-> AND t1.ID != t2.ID
-> ORDER BY source_row;
+------------+-------------+------+------+
| source_row | same_as_row | a_id | b_id |
+------------+-------------+------+------+
| 1 | 2 | 34 | 23 |
| 1 | 4 | 34 | 23 |
| 2 | 1 | 34 | 23 |
| 2 | 4 | 34 | 23 |
| 4 | 1 | 34 | 23 |
| 4 | 2 | 34 | 23 |
+------------+-------------+------+------+
6 rows in set (0.00 sec)
答案 3 :(得分:-1)
这是一个基本的SQL查询:
SELECT *
FROM my_table
WHERE a_id = b_id;
其中my_table是您的表名。