查询不返回NULL值 - SQL

时间:2018-02-20 09:42:14

标签: sql-server tsql

我一直在尝试改变我的查询,但没有运气!我有桌子:

Demographic
( name, gender, nationality, ethnicity etc)
Reference
(ID, Code as varchar, Description varchar)

基本上我将reference表中的所有值添加到nationality, Gender, ethnicity,然后将其链接到demographics,例如。 ID:1 , Code: Gender , Description: Male

因此在demographics male 1 Reference.ID Select Id, fname, Surname ,e.Description as Nationality ,a.Description as Gender FROM Demographics d, Reference e, Reference a WHERE (d.Nationality = e.ID OR d.Nationality IS NULL) AND (d.Gender = a.ID OR d.Gender IS NULL)

我写过这个问题:

let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

没有IS NULL部分它可以工作,但它排除了所有NULL值。但是当我添加IS NULL时,它会返回不准确的值,例如性别列中的我将具有种族值

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

这就是猜测,但是,我认为你的问题在于你正在编写SQL,就像你在1980年代那样。正如我在评论中所说,JOIN语法已存在数十年。停止为表使用分隔列表并使用隐式连接。

无论如何,我认为你需要的是LEFT JOIN

SELECT d.Id, d.fname, d.Surname,
       n.[Description] AS Nationality,
       g.[Description] AS Gender
FROM Demographics d
     LEFT JOIN Reference n ON d.Nationality = n.ID
     LEFT JOIN Reference g ON d.Gender = g.ID;

如果这不正确,那么将需要样本和预期结果。

答案 1 :(得分:0)

切换到不推荐使用的连接样式,并且正确的方式将是正确的:

Select Id, fname, Surname
         ,e.Description as Nationality
         ,a.Description as Gender
FROM Demographics d
LEFT JOIN Reference e 
  ON e.ID = d.Nationality
LEFT JOIN  Reference a
  ON a.ID = d.Gender

答案 2 :(得分:0)

您需要LEFT JOIN此处

Select Id, fname, Surname
         ,e.Description as Nationality
         ,a.Description as Gender
FROM Demographics d
    LEFT JOIN Reference e ON d.Nationality = e.ID
    LEFT JOIN Reference a ON d.Gender = a.ID

答案 3 :(得分:0)

尝试以下查询:

    Select Id, fname, Surname
             ,e.Description as Nationality
             ,a.Description as Gender
    FROM Demographics d, Reference e, Reference a
    WHERE   (d.Nationality = e.ID OR (e.ID IS NULL AND d.Nationality IS NULL)) 
    AND     (d.Gender = a.ID OR (a.ID IS NULL AND d.Gender IS NULL))

我稍微调整了你的查询。我认为你是在正确的道路上,只是错过了一点,与NULL比较。

当你检查一个可操作性的操作数(即IS NULL)而错过另一个操作数时,查询会给你所有关于缺少另一方的信息。

查看此Microsoft TechNet文章以获取进一步的学习内容:NULL Comparison Search Conditions - TechNet - Microsoft