带有内部联接的SQL Server NULL值

时间:2011-04-27 20:33:13

标签: c# sql null inner-join isnull

我正在使用C#和SQL Server。

看一下以下SQL:

SELECT table1.id, table1.description, table2.name, table2.surname 
FROM table1 
    INNER JOIN table2 ON table1.EmpID = table2.EmpID

直截了当,工作正常。它正确地从table1表中检索数据,并正确连接table1.empidtable2.nametable2.surname

现在,有时候table1.empid为空,当它出现时,这个SQL只会忽略带有空值的“行”;根据标准,这是很正常的。

我需要的是获取带有空值的“行”,当table1.empid为空时,我需要将自定义值设置为table2.nametable2.surname

我一直在玩isnull(),但我所做的就是让它变得更糟。

有什么建议吗?

由于

5 个答案:

答案 0 :(得分:10)

您需要进行LEFT JOIN:

SELECT table1.id, table1.description, table2.name, table2.surname FROM table1
LEFT JOIN table2 ON table1.EmpID = table2.EmpID;

答案 1 :(得分:0)

尝试使用UNION:

SELECT table1.id, table1.description, table2.name, table2.surname 
FROM table1 
INNER JOIN table2 ON table1.EmpID = table2.EmpID
UNION
SELECT table1.id, table1.description, 'Table 2 Null', 'Table 2 Null'
FROM table1
WHERE table1.empId is null

答案 2 :(得分:0)

Select table1.id table1.description
    , Case When table1.EmpID Is Null Then 'Some Value' Else table2.name End As Table2Name
    , Case When table1.EmpID Is Null Then 'Some Value' Else table2.surname End As Table2Surname
From table1
    Left Join table2
        On table2.EmpID = table1.EmpID
Where table1.EmpID Is Null
        Or table2.EmpID Is Not Null

答案 3 :(得分:0)

如果表1为空,您仍然需要无法启动的记录。从table2开始并加入table1。

SELECT table1.id, table1.description, ISNULL(table1.empid, "some new value") AS name, table2.surname 
FROM table2 
    LEFT OUTER JOIN table1 ON table2.EmpID = table1.EmpID

答案 4 :(得分:0)

SELECT table1.id
       ,table1.description
       ,COALESCE(table2.name, 'DEFAULT') AS name
       ,COALESCE(table2.surname, 'DEFAULT') AS surname
FROM table1 
LEFT JOIN table2
    ON table1.EmpID = table2.EmpID

现在请注意,当EmpID不为null时,这也将包括人,但如果他们在table1中有一个EmpID,那么它仍然是“无效”,但是在table2中找不到它,所以如果你要避免的话,那么另一个选项是这样的:

SELECT table1.id
       ,table1.description
       ,table2.name
       ,table2.surname
FROM table1 
INNER JOIN table2
    ON table1.EmpID = table2.EmpID

UNION ALL

SELECT table1.id
       ,table1.description
       ,'DEFAULT' AS name
       ,'DEFAULT' AS surname
FROM table1 
WHERE table1.EmpID IS NULL