用于替换TSQL的SQL语句

时间:2015-03-10 21:26:56

标签: sql sql-server-2008

请参阅下面的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。

4 个答案:

答案 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 BYHAVING

执行此操作
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) 

SQLFIDDLE DEMO