如何编写连接多个表的查询,这些表返回列为null的结果集

时间:2017-03-30 15:37:02

标签: mysql sql

如果我有这些表

address         quarter         
------------  ----------
address_id     quarter_id
quarter_id     quarter_name
address_name   quarter_code

如果用户提供地址信息(address_name),则会识别该季度,因为该地址在四分之一以内。但是,如果用户没有提供地址,而是提供四分之一的地址信息将无法使用。

Select      address.address_name, 
            quarter.quarter_code 
From        address 
some_join   quarter on  address.quarter_id = quarter.quarter_id 
where       address.address_name like @param 
or          quarter.quarter_code = @param

如果where子句与address_name条件匹配,我想要这样的结果。

address_name  | quarter_code
stress eight     14400459

但如果用户键入14400459

address_name  | quarter_code
null            14400459

我很难提出这个问题。自从我看到sql连接已经很长时间了,这种事情很容易让人忘记。

1 个答案:

答案 0 :(得分:2)

正确的加入可能很棘手;这是它应该如何构造,另外你想要第一个非空值来匹配参数:

select *
from address as a
right join quarter as q
on q.quarter_id = a.quarter_id
and coalesce(a.address_name, q.quarter_code) = @param

或者更好:

select *
from address as a
right join quarter as q
on q.quarter_id = a.quarter_id
and (
    a.address_name = @param
    or
    q.quarter_code = @param
    )