用于查找共享某些值但不共享其他值的对的SQL查询

时间:2015-11-14 17:13:02

标签: mysql sql distinct

我在为此问题创建查询时遇到了一些问题。

我需要找到哪些人WorkedOn彼此建立但没有Financed他们在一起。

我的表:

Build(person, financed, workedOn)

Person | Financed | WorkedOn
-----------------------------
Person1| Build1   | Build4
Person2| Build2   | Build5
Person3| Build1   | Build5
Person4| Build2   | Build3
Person5| Build3   | Build1
Person6| Build1   | Build5
Person7| Build4   | Build3
Person8| Build5   | Build3

正确的查询应该产生如下内容:

Person
-------
Person7  Person8
Person8  Person4
Person6  Person3

我尝试过使用distincthaving我似乎没有做到这一点。任何帮助将不胜感激,我使用sqlite3,谢谢:)

2 个答案:

答案 0 :(得分:2)

SELECT t1.person, t2.person
FROM build t1, build t2
WHERE t1.workedon = t2.workedon
AND t1.financed != t2.financed
AND t1.person > t2.person

SQL Fiddle

答案 1 :(得分:0)

您可以自我加入

以下是SQLFiddle Demo

输入enter image description here

<强>输出enter image description here

SELECT T1.Person,T2.Person,CONCAT(T1.Person,' ',T2.Person) AS Person
    FROM
          Build T1 
    INNER JOIN 
          Build T2 
    ON T1.WorkedOn = T2.WorkedOn AND T1.Financed <> T2.Financed 
   WHERE T1.Person < T2.Person

希望这有帮助。