我有一张如下表格:
| ID | Short Name | Long Name |
|----|------------|-----------|
| 1 | s1 | l2 |
| 2 | s1 | l2 |
| 3 | s1 | l2 |
| 4 | s5 | l6 |
| .. | ... | |
我希望获得所有共享相同短名称和长名称的记录。我需要他们共享的短名称,长名称和3个副本。标识。对于这个特例,我想要{s1,l2,1,2,3}
答案 0 :(得分:1)
这是一个相当简单的问题需要解决。基本上您要做的是编写一个子查询,该子查询计算查询中每行在指定字段上匹配的行数。我在下面列举了几个例子。
查找所有重复的行并在两个名称字段上匹配
SELECT * FROM TableName WHERE (SELECT COUNT(*) FROM TableName AS T2 WHERE T2.ShortName = TableName.ShortName AND T2.LongName = TableName.LongName) > 1;
查找所有重复的行并在短名称上匹配
SELECT * FROM TableName WHERE (SELECT COUNT(*) FROM TableName AS T2 WHERE T2.ShortName = TableName.ShortName) > 1;
查找所有重复的行并在长名称上匹配
SELECT * FROM TableName WHERE (SELECT COUNT(*) FROM TableName AS T2 WHERE T2.LongName = TableName.LongName) > 1;
答案 1 :(得分:0)
只需使用表格的自连接,然后选择两个名称相等且id
不同的行:
SELECT *
FROM <table> t1, <table> t2
WHERE t1.id <> t2.id
AND t1.short_name = t2.short_name
AND t1.long_name = t2.long_name;
答案 2 :(得分:0)
您可以使用exits
查看是否存在任何其他数据存在且ID不相同的相同条件。
select t1.* from table_name t1
where exists (
select 1 from table_name t2
where
t1.ID <> t2.ID
and t1.`Short Name` = t2.`Short Name`
and t1.`Long Name` = t2.`Long Name`
);