[英]Mysql Complex Join Query Issue
我有5個mysql表,如下所述。 診所表
id
name
d_location_subscription表
id
clinic_id
t_id //t_id will contain a foreign key of d_cities, d_states or d_countries table
type "country" "state" "city"
d_countries表
id
name
code
d_states表
id
d_country_id
name
code
d_city表
id
d_state_id
name
code
d_location_subscription表用於記錄診所對某個位置(可能是城市,州或國家)的訂購。 我期望使用d_location_subscription表獲取特定診所的所有訂閱城市。
例如,如果診所A已訂閱德克薩斯州,則我應該能夠獲得診所A的所有城市ID。
我創建以下sql查詢,它看起來很丑,但是生成了我想要實現的接近結果。
select
`d`.`id` AS `clinic_id`,
if((`dct`.`id` is not null),`dct`.`id`,if((`dct1`.`id` is not null),`dct1`.`id`,`dct2`.`id`)) AS `d_city_id`
from ((((((((
`d_location_subscriptions` `dls`
join `clinics` `d`
on((`d`.`id` = `dls`.`clinic_id`)))
left join `d_countries` `dc`
on(((`dc`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'country'))))
left join `d_states` `ds`
on((`ds`.`d_country_id` = `dc`.`id`)))
left join `d_cities` `dct2`
on((`dct2`.`d_state_id` = `ds`.`id`)))
left join `d_states` `ds1`
on(((`ds1`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'state'))))
left join `d_cities` `dct`
on((`dct`.`d_state_id` = `ds1`.`id`)))
left join `d_cities` `dct1`
on(((`dct1`.`id` = `dls`.`t_id`) and (`dls`.`type` = 'city'))))
)
當d_location_subscription表中有類型為“ country”的記錄時,我收到以下結果。 返回的記錄總數等於d_states表記錄的數目。
如何通過更改上面的查詢來擺脫那些Null值? 並且請告訴我這是否是實現類似功能的正確方法。 提前致謝 :)
實現所需目標的最快,最骯臟的方法就是將以下where條件附加到查詢中:
WHERE d_city_id is not null
但您可能希望對查詢進行重新處理,並確定真正需要LEFT聯接而不是INNER聯接的位置
實際上,IF()計算列就是STT LCU試圖提供的列,但是由於某種原因,您不能在where中直接使用它。
我已經重寫了您的查詢,但是使用了不同的別名以更好地遵循表/關系的起源來獲取數據。 最后,我添加了一個位置來測試“ ID”值中的任何一個是否為NOT NULL。 如果它們為ALL Null,則應排除該記錄。
select
d.id AS clinic_id,
if(CityViaState.id is not null, CityViaState.id,
if( ByCity.id is not null, ByCity.id, CityViaCountry.id )) AS d_city_id
from
d_location_subscriptions dls
join clinics d
ON dls.clinic_id = d.id
left join d_countries ByCountry
ON dls.t_id = ByCountry.id
and dls.type = 'country'
left join d_states StateViaCountry
ON ByCountry.id = StateViaCountry.d_country_id
left join d_cities CityViaCountry
ON StateViaCountry.id = CityViaCountry.d_state_id
left join d_states ByState
ON dls.t_id = ByState.id
and dls.type = 'state'
left join d_cities CityViaState
ON ByState.id = CityViaState.d_state_id
left join d_cities ByCity
ON dls.t_id = ByCity.id
and dls.type = 'city'
where
CityViaState.id is not null
OR ByCity.id is not null
OR CityViaCountry.id is not null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.