0

我有 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 值?如果这是实现类似功能的正确方法,请告诉我。提前致谢 :)

4

2 回答 2

1

实现您想要的最快、最肮脏的方法就是将此 where 条件附加到您的查询中:

WHERE d_city_id is not null

但您可能更愿意重新处理您的查询并确定您真正需要左连接而不是内部连接的位置

于 2013-09-16T15:37:18.220 回答
0

IF() 计算列本质上是 STT LCU 试图提供的,但由于某种原因,您不能直接在 where 中使用它。

我已经重写了您的查询,但使用不同的别名以更好地跟踪表/关系的起源以获取数据。最后,我添加了一个用于测试任何一个“ID”值是否为 NOT NULL 的位置。如果它们全部为 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
于 2013-09-16T16:01:58.213 回答