如何有效地反转多对多SQL查询?

时间:2010-07-12 11:19:35

标签: sql sql-server tsql

我有多对多的关系,我在其中查询所有具有特定N 的M,例如:

SELECT M.* FROM M INNER JOIN ManyToManyTable
ON M.Id = ManyToManyTable.M
WHERE ManyToManyTable.N = @Id

或者:

SELECT M.* FROM M INNER JOIN ManyToManyTable
ON M.Id = ManyToManyTable.M
INNER JOIN N
ON N.Id = ManyToManyTable.N
WHERE N.Id = @Id

我的问题是,如何有效地反转查询,以便所有M 没有特定的N

就像上面选择的NOT IN一样,但如果可能的话,没有NOT IN语句。

2 个答案:

答案 0 :(得分:5)

在SQL Server中,“NOT EXISTS”通常是more efficient,而不是OUTER JOIN方法。

SELECT M.* FROM M  
WHERE NOT EXISTS
 (SELECT * FROM ManyToManyTable MMT
           WHERE MMT.M = M.Id AND N=@Id )

答案 1 :(得分:1)

又快又脏:

SELECT M.* FROM M
WHERE M.id NOT IN
    (SELECT M.id FROM M INNER JOIN ManyToManyTable
     ON M.Id = ManyToManyTable.M
     WHERE ManyToManyTable.N = @Id)

更好:

SELECT M.*
FROM M LEFT JOIN ManyToManyTable
ON M.Id = ManyToManyTable.M
WHERE ManyToManyTable.M IS NULL