多表连接查询问题

select
	p.id,p.full_name,p.short_name,p.py_code,p.building_type,d.name
from
	tb_project p,tb_dict_entity d 
where d.`code`=p.building_type 
and d.type_code='PROJECT_BUILDING_TYPE'
and p.id = 257

tb_project: 项目表;
tb_dict_entity: 字典表。

项目表中的building_type字段对应字典表的code字段,但building_type并不是必须的。
这就造成,如果building_type字段有值,那么可以查出数据。

image_1bub6gke81eh2143415hc1v8e1vu11g.png-25kB

但如果building_type字段没有值,是查不出数据的,因为字典表中没有为null的code.

image_1bub6heqn1g6dhii1m26qupbpc1t.png-22.6kB

换成左外连接也不行

image_1bub6j47e1one6jh107s18fs19e32a.png-27.5kB

这样就可以了:

select
	p.id,p.full_name,p.short_name,p.py_code,p.building_type,d.name
from
	tb_project p left join tb_dict_entity d on d.`code`=p.building_type and d.type_code='PROJECT_BUILDING_TYPE'
where p.id = 258

image_1bub6kcjnkccu681smc10qg13pc2n.png-32.3kB

多表左外连接也是一样的道理:

select
	p.id,p.full_name,p.short_name,p.py_code,p.building_type,d.name as building_type_str,p.climate_type,d2.name as climate_type_str
from
	tb_project p left join tb_dict_entity d on d.`code`=p.building_type and d.type_code='PROJECT_BUILDING_TYPE'
	left join tb_dict_entity d2 on d2.`code`=p.climate_type and d2.type_code='SYS_ClimateArea'
where p.id=258

image_1bucla3bk1kj4acji8c1dkn6b89.png-26.9kB

原文地址:https://www.cnblogs.com/VitoYi/p/7800872.html