从具有OR条件

时间:2016-01-29 21:03:20

标签: sql sql-server

我使用的是SQL Server,而且我很难尝试从我想要的SELECT查询中获取结果。我可以从以下3个表中选择记录:

客户端(clientID,name,age,dateOfBirth)

地址(clientID,city,street)

电话(ClientID,personalPhone,officePhone,homePhone)

在我的输入中我可以拥有(dateOfBirth,steet,homePhone),我需要在结果中使用Disntinct ClientID。这些输入值是可选的。每次所有这些输入值都有价值时,并非强制要求,在某些情况下,只提供street和homePhone,或者有时只提供街道。

有" OR"争论中的关系!就好,如果我通过homePhone,即使那时应该返回记录。

3 个答案:

答案 0 :(得分:0)

您可以使用or条件来短路逻辑。我们假设你用@

表示参数
SELECT    DISTINCT client_id
FROM      client c
LEFT JOIN address a ON c.client_id = a.client_id
LEFT JOIN phone p ON c.client_id = p.client_id
WHERE     (@date_of_birth IS NULL OR c.date_of_birth = @date_of_birth) AND
          (@street IS NULL OR @street = a.street) AND
          (@home_phone IS NULL OR @home_phone = p.home_phone)

答案 1 :(得分:0)

这与Mureinik的答案几乎相同,但他没有使用左外连接,所以如果你有一个地址但没有电话号码的客户,他们将被排除在结果之外-set除非您使用外连接:

SELECT DISTINCT client_id
FROM   client c
LEFT OUTER JOIN   address a 
    ON c.client_id = a.client_id
LEFT OUTER JOIN   phone p 
    ON c.client_id = p.client_id
WHERE  (@date_of_birth IS NULL OR c.date_of_birth = @date_of_birth) AND
       (@street IS NULL OR @street = a.street) AND
       (@home_phone IS NULL OR @home_phone = p.home_phone)

答案 2 :(得分:0)

默认为“all”或通配符的null的标准方式如下:

SELECT *
FROM client c
LEFT JOIN address a ON c.client_id = a.client_id
LEFT JOIN phone p ON c.client_id = p.client_id
WHERE (COALESCE(@date_of_birth,c.date_of_birth) = c.date_of_birth 
    OR COALESCE(@street,c. a.street) =  a.street
    OR COALESCE(@home_phone,p.home_phone) = p.home_phone )
 -- Put the following line in if you want at least one parameter to not be null
 AND COALESCE(@date_of_birth,@street,@home_phone) is not null