20

我相当肯定这很简单,但是我尝试过的每个示例都失败了。我想查询这样的表

ID   Part_Type   Station_Type
---  ---------   ------------
1    5           234
2    5           846
3    5           234
4    6           585
5    6           585
6    7           465

并返回第 1 行和第 3 行,以及第 4 行和第 5 行。也就是说,我想返回其中两列匹配的行。它类似于这个问题:SO Question但只需要在一张桌子上完成。该查询将为每一行找到一个匹配项,但我只想要在两列中具有匹配值的行。我怎么去找到那个?

谢谢

4

3 回答 3

24

您可以使用以下内容:

select t1.id, t1.part_type, t1.station_type
from yourtable t1
where exists (select part_type, station_type
              from yourtable t2
              where t1.part_type = t2.part_type
                and t1.station_type = t2.station_type
              group by part_type, station_type
              having count(id) > 1)

请参阅带有演示的 SQL Fiddle

于 2013-02-26T23:32:44.337 回答
4
select id, part_type, station_type 
from myTable t1
where exists (select 1 from myTable t2
              where t1.part_type = t2.part_type
                  and t1.station_type = t2.station_type
                  and t1.id <> t2.id)
于 2013-02-26T23:35:14.673 回答
1

我认为自我加入对您有用:

SELECT * FROM table t1 
INNER JOIN table t2 ON t1.Part_Type = t2.Part_Type 
  AND t1.Station_Type = t2.Station_Type
  AND t1.Id <> t2.Id
于 2013-02-26T23:29:16.370 回答