SQL Server NOT EXISTS来自多个表

时间:2010-06-16 14:48:55

标签: sql sql-server performance tsql

如果存在,我需要返回行,如果没有返回哪个传递的值不是EXISTS:

DECLARE @INPUT1 BIGINT
DECLARE @INPUT2 BIGINT
DECLARE @INPUT3 BIGINT

SELECT e.Name, d.Name, c.Name
   FROM Employee e
   JOIN Department d ON e.DeptID = d.DeptID
   JOIN City c ON e.CityID = c.CityID
WHERE
   e.EmpID = @INPUT1
   AND d.DeptID = @INPUT2
   AND c.CityID = @INPUT3

在上面的SQL中,所有输入INPUT1,INPUT2,INPUT3都正确传入,返回行。如果不是,我需要找出哪个INPUTx是错误的。我知道我可以编写3个不同的Exists查询来查找哪个不存在。有更好的方法吗?提前谢谢。

2 个答案:

答案 0 :(得分:0)

您不能使用(内部)联接,因为这会消除那些不匹配的记录。因此,您必须使用外部联接。鉴于此,无论如何使用3个查询可能会更快。实际上,4,因为你需要3来检查3个值,然后另一个返回你想要的那个值。

你可以这样做:

SELECT 'Employee Exists' as Result from Employee where EmpId = @INPUT1
union
SELECT 'Department Exists' from Department where DeptId = @INPUT2
union
SELECT 'City Exists' from City where CityId = @INPUT3

显示哪些不存在,然后返回您对查询的作用。我想你可以把它组合成3列而不是3行,但它仍然是3个查询。

答案 1 :(得分:0)

您想要的确切逻辑不清楚,但此构造将过滤器应用为派生表,您可以将其连接起来。因此,如果d.Name为空,则在@ INPUT2

上不匹配
DECLARE @INPUT1 BIGINT, @INPUT2 BIGINT, @INPUT3 BIGINT

SELECT
    @INPUT1 AS NotThereIf_eName_IsNull,
    @INPUT2 AS NotThereIf_dName_IsNull,
    @INPUT3 AS NotThereIf_cName_IsNull,
    e.Name, d.Name, c.Name
FROM
    (SELECT @INPUT1 AS EmpID,  @INPUT2 AS DeptID, @INPUT3 AS CityID) dummy
    LEFT JOIN 
    Employee e ON dummy.EmpID = e.EmpID
    LEFT JOIN 
    Department d ON dummy.DeptID = d.DeptID AND e.DeptID = d.DeptID
    LEFT JOIN 
    City c ON dummy.CityID = c.CityID AND e.CityID = c.CityID