我的表与下面的表类似。我想选择城市和城镇匹配的记录,代码或区域重复。在这种情况下,行结果应该是除了id为3和5之外的所有行。感谢您查看此
city town id code1 code2 code3 code4 area1 area2 area3 area4
----------------------------------------------------------------------------------
dublin town1 1 1 2 3 5 1 2 3 4
dublin town1 2 2 8 10 6 7 8 9
dublin town1 3 12 13 15 11 12 13 14
dublin town2 4 1 2 3 5 1 2 3 4
dublin town2 5 6 7 8 10 6 7 8 9
dublin town2 6 11 12 13 15 1 12 13 14
答案 0 :(得分:1)
这几乎是exists
子句可以做的事情。这是您的条件的解决方案:
select t.*
from <table> t
where exists (select 1
from <table> t2
where t2.city = t.city and
t2.town = t.town and
t2.id <> t.id and
(t2.code1 = t.code1 or t2.code2 = t.code2 or t2.code3 = t.code3 or t2.code4 = t.code4 or
t2.area1 = t.area1 or t2.area2 = t.area2 or t2.area3 = t.area3 or t2.area4 = t.area4
)
答案 1 :(得分:1)
使用INNER JOIN,
select a.*
from bigcities a inner join bigcities b
on a.city = b.city
and a.town = b.town
and a.id != b.id
and (a.code1 = b.code1
or a.code2 = b.code2
or a.code3 = b.code3
or a.code4 = b.code4
or a.area1 = b.area1
or a.area2 = b.area2
or a.area3 = b.area3
or a.area4 = b.area4
);
答案 2 :(得分:0)
您可以使用以下查询
执行此操作--We do a query to the table to get the rows and then we do a subquery
--to get all the rows with the same criteria. We know it is repeated
--because the counter of rows > 1.
--If you want to get only where it is repeated 2 o 3, etc, you only need to change
--the COUNT() > 1
SELECT *
FROM tableName t
WHERE (
SELECT COUNT(*) FROM tableName tRep WHERE
t.city = tRep.city AND
t.town = tRep.town AND
((t.code1 = tRep.code1 AND t.code2 = tRep.code2 AND t.code3 = tRep.code3 AND t.code4 = tRep.code4) OR
(t.area1 = tRep.area1 AND t.area2 = tRep.area2 AND t.area3 = tRep.area3 AND t.area4 = tRep.area4))
) > 1