多级级联内连接选择查询

时间:2016-10-14 12:57:22

标签: sql database postgresql

我遵循表格结构 enter image description here

我想从short_name(国家/地区名称),名称(州名表)或region_name的任何可用数据中选择post_id。对region_name执行以下查询true结果,但不执行short_name(国家/地区名称),名称(状态表)。

select *
from t_post_city
inner join t_region on t_region.region_id = t_post_city.city_id
inner join t_country on t_region.country_id = t_country.country_id
inner join t_states on t_region.province_id = t_states.state_id
where t_country.short_name like %india%
   or t_states.name like %rajasthan%
   or t_region.region_name like %sitapura%

请告诉我,我在哪里错了!

2 个答案:

答案 0 :(得分:2)

select *
from t_post_city
LEFT OUTER join t_region on t_region.region_id = t_post_city.city_id
LEFT OUTER join t_country on t_region.country_id = t_country.country_id
LEFT OUTER join t_states on t_region.province_id = t_states.state_id
 where t_country.short_name like '%india%'
 or t_states.name like '%rajasthan%'
 or t_region.region_name like '%sitapura%'

答案 1 :(得分:1)

为三个条件中的每一个使用不同的表表达式。在SQL中使用OR编写UNION逻辑:

select post_id
from t_post_city
inner join t_region on t_region.region_id = t_post_city.city_id
where t_country.short_name like %india%
t_region.region_name like %sitapura%
union
select post_id
from t_post_city
inner join t_region on t_region.region_id = t_post_city.city_id
inner join t_country on t_region.country_id = t_country.country_id
where t_country.short_name like %india%
union
select post_id
from t_post_city
inner join t_region on t_region.region_id = t_post_city.city_id
inner join t_states on t_region.province_id = t_states.state_id
where t_states.name like %rajasthan%;
相关问题