关于转换left join on 写法的问题
有2个表关联的查询,consult_booking表中illness_condition可能为空,用如下写法可以查询到对应consult_booking表中的所有数据
select *
from consult_booking a
left join code b
on a.illness_condition = b.code
and b.code_type_id = 17;
但如果通过
select *
from consult_booking a, code b
where b.code_type_id = 17
and (a.illness_condition = b.code or a.illness_condition is null);
查询的话,查询结果中consult_booking表中illness_condition不为空的查询到consult_booking表和对应的code表组合起来的字段的完整数据,但如果consult_booking表中illness_condition为空时,查询到的结果为code表中对应类型所有数据consult_booking表和对应的code表所有类型结果的数据,求解决方法
------解决方案--------------------首先不知道为什么不让用join 你们领导想考你吗?这种需求,最好的办法就是用join啊
其次 你的sql
select *
from consult_booking a, code b
where b.code_type_id = 17
and (a.illness_condition = b.code or a.illness_condition is null);
有问题,如果a.illness_condition = b.code,这是一个等值连接,没问题
如果a.illness_condition is null,你的sql就变成
select *
from consult_booking a, code b
where b.code_type_id = 17
and a.illness_condition is null;
这就是a和b两个表的笛卡尔积 当然有问题了
我建议你把这个or改为union
sql为:
select *
from consult_booking a, code b
where b.code_type_id = 17
and a.illness_condition = b.code
union
select a.*, '' as id, '' as code_type_id, '' as value
from a
where a.illness_condition is null;