一、问题
用以下sql语句查询数据,结果为空
SELECT a.ID , a.Sub_Project_Name , a.Sub_Project_Type FROM TB_KYSubProject a WHERE a.ID NOT IN ( SELECT DISTINCT c.SubprojectID FROM TB_KYGrogramme c WHERE ISNULL(c.Belong_Programme, ‘‘) <> ‘‘ AND c.Belong_Programme IN ( SELECT ConfigValue FROM PB_Config WHERE ConfigKey = ‘子项目共有所属方案‘ ) )
但是查询TB_KYGrogramme和TB_KYSubProject都有数据,TB_KYSubProject比TB_KYGrogramme的数据还多,不应该没数据
TB_KYGrogramme
SELECT DISTINCT c.SubprojectID FROM TB_KYGrogramme c WHERE ISNULL(c.Belong_Programme, ‘‘) <> ‘‘ AND c.Belong_Programme IN ( SELECT ConfigValue FROM PB_Config WHERE ConfigKey = ‘子项目共有所属方案‘ )
TB_KYSubProject
SELECT DISTINCT a.ID FROM TB_KYSubProject a
后面筛选TB_KYGrogramme,有一条数据SubprojectID是NULL
SELECT DISTINCT c.SubprojectID FROM TB_KYGrogramme c WHERE ISNULL(c.Belong_Programme, ‘‘) <> ‘‘ AND c.Belong_Programme IN ( SELECT c.ConfigValue FROM PB_Config c WHERE c.ConfigKey = ‘子项目共有所属方案‘ ) AND c.SubprojectID IS NULL
二、原因
SELECT 1 AS id , 1 AS subprojectid UNION SELECT 2 AS id , 2 AS subprojectid UNION SELECT 3 AS id , 3 AS subprojectid UNION SELECT 4 AS id , NULL AS subprojectid
SELECT * FROM ( SELECT 1 AS id , 1 AS subprojectid UNION SELECT 2 AS id , 2 AS subprojectid UNION SELECT 3 AS id , 3 AS subprojectid UNION SELECT 4 AS id , NULL AS subprojectid ) vv WHERE subprojectid NOT IN ( 1, NULL )
等同
SELECT * FROM ( SELECT 1 AS id , 1 AS subprojectid UNION SELECT 2 AS id , 2 AS subprojectid UNION SELECT 3 AS id , 3 AS subprojectid UNION SELECT 4 AS id , NULL AS subprojectid ) vv WHERE subprojectid <> 1 AND subprojectid <> NULL
NULL值不能参与比较运算符,要筛选非NULL数据,要用 is not null,而不能用<>NULL,具体看下数据库中的三值逻辑(Tree-Value-Logic)。
所以子查询有结果是NULL,那查询条件为空
三、方法
知道问题原因,对sql语句修改,把SubprojectID是NULL的数据排查
SELECT a.ID , a.Sub_Project_Name , a.Sub_Project_Type FROM TB_KYSubProject a WHERE a.ID NOT IN ( SELECT DISTINCT c.SubprojectID FROM TB_KYGrogramme c WHERE ISNULL(c.Belong_Programme, ‘‘) <> ‘‘ AND c.Belong_Programme IN ( SELECT ConfigValue FROM PB_Config WHERE ConfigKey = ‘子项目共有所属方案‘ ) AND c.SubprojectID IS NOT NULL)
开发中遇到该问题记录下
原文地址:https://www.cnblogs.com/Zev_Fung/p/8488107.html
时间: 2024-10-11 00:03:42