从一个表中选择与SQL中另一个表中的相同值关联的唯一行对

时间:2014-06-12 20:50:03

标签: sql

我有三个表:DollsDressesWho wears what

玩偶表:

Names    ID

礼服表:

Descriptions    ID

谁穿什么表:

Doll_ID   Dresses_ID

我如何找出哪两个娃娃穿同样的衣服。我只想要独特的配对。我管理的最好的是这个,但它没有给出独特的配对:

SELECT 
    "Dolls"."Name", "Dolls2"."Name", "Dresses"."Description" AS "Dresses" 
FROM 
    "Dolls", "Dolls" AS "Dolls2", "Who wears what" AS "WWW", 
     "Who wears what" AS "WWW2", "Dresses" 
WHERE 
    "WWW"."Panenka" = "Dolls"."ID"
    AND "WWW2"."Panenka" = "Dolls2"."ID" 
    AND "Dresses"."ID" = "WWW"."Dresses" 
    AND "Dresses"."ID" = "WWW2"."Dresses" 
    AND "Dolls"."ID" != "Dolls2"."ID"

示例数据:

娃娃

1, Vera
2, Mary
3, Viki

连衣裙

1, Short
2, Skimpy
3, See-through

WWW(娃娃,连衣裙)

1, 1
2, 1
3, 3

期望的输出:

Vera, Mary, Short

1 个答案:

答案 0 :(得分:1)

一种可能性是从WWW获得由多个娃娃打扮的连衣裙,获得相关的Doll_IDMINMAX,因为只需要2个)和JOIN这些ID回到玩偶表

SELECT d1.Names Doll_1, d2.Names Doll_2, Dress.Descriptions
FROM   Dolls d1
       INNER JOIN (SELECT max(Doll_ID) D1ID, min(Doll_ID) d2ID, D.Descriptions
                   FROM   WWW W
                          INNER JOIN Dresses D ON W.Dresses_ID = D.ID
                   GROUP BY D.Descriptions
                   HAVING   COUNT(DISTINCT Doll_ID) > 1) Dress 
               ON d1.ID = Dress.d1ID
       INNER JOIN Dolls d2 ON d2.ID = Dress.d2ID

SQLFiddle demo

两个玩偶必然会有所不同,因为如果有多个不同的ID MINMAX不能是相同的值