我的查询仍在返回具有空值的行

tcbh2hod  于 2022-09-18  发布在  Java
关注(0)|答案(4)|浏览(147)

我正在尝试编写一个只返回一组列没有任何空值的行的查询。

如果结果中的任何一列有空值,我不希望返回任何行:

gameTitle, gameDevTeam, gameType, innerId/outerId, prodCode, teamCode

所以我做了一些搜索,发现了这个问题:

Optimize way of Null checking for multiple columns

当我尝试将该逻辑应用于我的查询时,我仍然看到有一列或多列为空的结果。

以下是我的疑问:

SELECT  *
FROM  GameData gd
WHERE gd.dev_Status = 002
  AND COALESCE(gd.gameTitle, gd.gameDevTeam, gd.gameType, COALESCE(gd.innerId, gd.outerId), gd.prodCode, gd.teamCode) IS NOT NULL
  AND gd.gameType IN(003, 004)

我有什么地方做错了吗?

q8l4jmvw

q8l4jmvw1#

从逻辑上讲,您要求any列的反义词是NULL,因此以下模式有望对您起作用:

select * 
from t
where not( col1 is null or col2 is null or col3 is null or ...);
flvlnr44

flvlnr442#

您指定的那个链接显示了一个解决方案,该解决方案正在检查任何列是否不为空。听起来您似乎是在尝试检查所有列是否都不为空。如果这是正确的,那么你可以这样做:

AND gd.gameTitle IS NOT NULL
AND gd.gameDevTeam IS NOT NULL
AND gd.innerId IS NOT NULL
...repeat for every column you care about
e0uiprwp

e0uiprwp3#

您可以将CONCAT_NULL_YIELDS_NULL设置为ON,然后将列作为文本添加。
如果其中任何一列为空,则它们的总和也将为空。

SET CONCAT_NULL_YIELDS_NULL ON

select * from (values 
    ('gameTitle1', 'gameDevTeam1', 'gameType', 1, 2, 'prodCode1', 'teamCode1'),
    ('gameTitle2', 'gameDevTeam2', null, 1, 2, 'prodCode2', 'teamCode2'),
    ('gameTitle3', 'gameDevTeam3', 'gameType', null, 2, 'prodCode3', 'teamCode3')
)t(gameTitle, gameDevTeam, gameType, innerId, outerId, prodCode, teamCode)
WHERE 
    (gameTitle + gameDevTeam + gameType + cast(innerId as varchar(50)) + cast(outerId as varchar(50)) + prodCode + teamCode) is not null
amrnrhlw

amrnrhlw4#

I think it's down to your COALESCE. Try taking the gameType out of the mix. In theory, if your game type is set, then all your other fields after this could be null, as per my comment...

SELECT  *
FROM  GameData gd
WHERE gd.dev_Status = 002
     AND COALESCE(gd.gameTitle, gd.gameDevTeam, gd.innerId, gd.outerId, gd.prodCode, gd.teamCode) IS NOT NULL
     AND gd.gameType IN(003, 004)

I think your approach could work using COALESCE, however @Anssss's answer may be more readable.

Just on the same track - should your ID fields also be in this list? Won't they be given a default number?

相关问题