0

我的表格与下面的类似。我想选择城市和城镇匹配且代码或区域重复的记录。在这种情况下,行的结果应该是除 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

http://sqlfiddle.com/#!2/0bbe7/1/0

4

3 回答 3

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
              )
于 2013-08-29T21:16:35.273 回答
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
         );

演示

于 2013-08-30T09:25:11.973 回答
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
于 2013-08-30T02:54:31.970 回答