Mysql Complex加入查询问题

时间:2013-09-16 15:33:55

标签: php mysql

我有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 table

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表记录的数量。

this is the result

如何通过更改上述查询来消除那些Null值? 如果这是实现类似功能的正确方法,请告诉我。在此先感谢:)

2 个答案:

答案 0 :(得分:1)

实现目标的最快捷,最脏的方法就是将其附加到查询条件中:

WHERE d_city_id is not null

但您可能更愿意重新设计查询并确定您真正需要LEFT连接的位置而不是INNER连接

答案 1 :(得分:0)

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

我已经重写了你的查询,但是使用不同的别名来更好地遵循表/关系的起源来获取数据。最后,我添加了一个测试任何一个“ID”值为NOT 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
相关问题