2012-01-27 60 views
0

我认为我的where子句是错误的。SQL查询不能让我感觉

我的两难处境是,如果用户在tbl_dentalBuyerInsurance中没有记录,那意味着他们正在采取所有措施。

因此,如果用户在tbl_dentalBuyerInsurance中没有记录,我希望他们作为结果返回。 我也希望他们回来,如果他们在tbl_dentalBuyerInsurance中有记录,并且它使用LIKE或相等匹配。

SELECT 
[dbo].[tbl_users].*, [dbo].[tbl_dentalBuyerInsurance].* 
    FROM 
[dbo].[tbl_users] 
    LEFT OUTER JOIN [dbo].[tbl_dentalBuyerInsurance] ON [dbo].[tbl_dentalBuyerInsurance].buyerId = [dbo].[tbl_users].id 
    LEFT OUTER JOIN [dbo].[tbl_dentalInsurance] ON [dbo].[tbl_dentalInsurance].id = [dbo].[tbl_dentalBuyerInsurance].dentalInsuranceId 
    WHERE 
(
    (
     [dbo].[tbl_dentalInsurance].companyName LIKE '%Cigna%' 
     OR [dbo].[tbl_dentalInsurance].companyName = '' 
    ) 
    AND(
     [dbo].[tbl_dentalBuyerInsurance].ppo = 1 
     OR [dbo].[tbl_dentalBuyerInsurance].ppo = '' 
    ) 
    AND(
     [dbo].[tbl_dentalBuyerInsurance].hmo = 0 
     OR [dbo].[tbl_dentalBuyerInsurance].hmo = '' 
    ) 
) 
+2

你真的应该尝试使用别名你的表。 – Aaron 2012-01-27 17:41:43

+0

会做:) @ BryceAtNetwork23 – 2012-01-27 17:57:48

回答

3

鉴于你使用LEFT连接,如果没有匹配的记录上的加入了“右”侧,所有的右侧字段将NULL,而不是空字符串。您必须明确检查.... OR whatever IS NULL,因为NULL不能等于任何东西,包括它本身。

+0

因此,这是有道理的? 'WHERE \t( \t \t( \t \t \t [DBO]。[tbl_dentalInsurance] .companyName LIKE '%信诺%' \t \t \t OR [DBO]。[tbl_dentalInsurance] .companyName IS NULL \t \t) \t \t AND( \t \t \t [DBO]。[tbl_dentalBuyerInsurance] .ppo = 1 \t \t \t OR [DBO]。[tbl_dentalBuyerInsurance] .ppo IS NULL \t \t) \t \t AND( \t \t \t [DBO]。[tbl_dentalBuyerInsurance] .hmo = 0 \t \t \t OR [DBO]。[tbl_dentalBuyerInsurance]。 hmo IS NULL \t \t) \t)' – 2012-01-27 17:48:26

+0

Thank you @Marc B ... This was helpful。 – 2012-01-27 18:00:39

1
[dbo].[tbl_dentalInsurance].companyName LIKE '%Cigna%' 
     OR [dbo].[tbl_dentalInsurance].companyName = '' 

这意味着你是allowinf空字符串,这是你的第一个错误,怎么说MarcB如果您正在寻找空值,以便查询是:

[dbo].[tbl_dentalInsurance].companyName LIKE '%Cigna%' 
     OR [dbo].[tbl_dentalInsurance].companyName is null 

如果允许空字符串所以你必须使用len函数用于验证值与lenght 0

saludos

+0

谢谢MarcB的回答是正确的:) – 2012-01-27 18:01:11