请参阅下面的DDL:
CREATE Table Person (PersonID int)
INSERT INTO Person (1)
INSERT INTO Person (2)
INSERT INTO Person (3)
INSERT INTO Person (4)
INSERT INTO Person (5)
CREATE TABLE PersonCrime (PersonID in,CrimeID int)
INSERT INTO PersonCrime (1,1)
INSERT INTO PersonCrime (2,1)
INSERT INTO PersonCrime (3,2)
INSERT INTO PersonCrime (9,3)
INSERT INTO PersonCrime (4,3)
我想从PersonCrime返回所有人员在人员表中的所有罪行。例如,返回犯罪1,因为人1和2在人员表中。犯罪2也被归还,因为人3在人员表中。犯罪3不归还,因为即使是人4,人9也不在人员表中。
我使用TSQL完成了这项工作,即绕过所有犯罪行为并检查所有人员。但是,这需要很长时间。我正在尝试使用SQL。
答案 0 :(得分:1)
为了清晰起见,使用表变量:
DECLARE @IgnoreCrime TABLE (CrimeID int);
INSERT INTO @IgnoreCrime SELECT CrimeID FROM PersonCrime WHERE PersonID NOT IN (SELECT PersonID FROM Person)
SELECT DISTINCT(CrimeID) FROM PersonCrime WHERE CrimeID NOT IN (SELECT CrimeID FROM @IgnoreCrime)
不
SELECT DISTINCT(CrimeID)
FROM #PersonCrime
WHERE CrimeID NOT IN
(SELECT CrimeID
FROM #PersonCrime
WHERE PersonID NOT IN (SELECT PersonID FROM #Person))
答案 1 :(得分:1)
您可以使用GROUP BY
和HAVING
:
SELECT CrimeID
FROM PersonCrime PC
LEFT JOIN Person P
ON PC.PersonID = P.PersonID
GROUP BY CrimeID
HAVING MIN(CASE WHEN P.PersonID IS NULL THEN 1 ELSE 2 END) <> 1
演示:SQL Fiddle
答案 2 :(得分:1)
另一种方式定义 - “在CrimeID
表格中没有PersoinID
的地方给我所有Person
:
SELECT DISTINCT CrimeID
FROM PersonCrime pc
WHERE NOT EXISTS
(
SELECT 1 FROM PersonCrime
WHERE CrimeID = pc.CrimeID
AND PersonID NOT IN (SELECT PersonID FROM PERSON)
)
答案 3 :(得分:0)
使用Exists
运营商查找personID
中的Person
,然后尝试此操作。
SELECT DISTINCT CrimeID
FROM PersonCrime PC
WHERE EXISTS (SELECT 1
FROM Person P
WHERE p.PersonID = pc.PersonID)
GROUP BY CrimeID
HAVING Count(CrimeID) = (SELECT Count(1)
FROM PersonCrime PC1
WHERE PC.CrimeID = PC1.CrimeID)