以某种方式创建我想要的查询不成功。
DB与位置有关,有以下相关的表
t_location
- 包含的位置列表字段t_location_zipcode
和t_location_id_location
t_zipcodecity
- 加入表格t_zipcodecity_zipcode t_zipcodecity_id_city t_city
- 包含t_city_id_city
t_citystate
- join table,t_citystate_id_city,t_citystate_id_state t_state
- 包含t_state_id_state 最初,我尝试使用此查询获取包含位置的状态列表:
SELECT DISTINCT `t_state_id_state`
, `t_state_name_full`
FROM (`t_state`)
LEFT JOIN `t_citystate` ON `t_state_id_state` = `t_citystate_id_state`
LEFT JOIN `t_city` ON `t_citystate_id_state` = `t_city_id_city`
LEFT JOIN `t_zipcodecity` ON `t_city_id_city` = `t_zipcodecity_id_city`
LEFT JOIN `t_location` ON `t_zipcodecity_zipcode` = `t_location_zipcode`
ORDER BY `t_state_name_full` asc
工作正常。
现在我需要/想要的是我失败的是获得每个州的位置数量。我不知道是否可以在这一个查询中完成,或者我是否需要另一个查询,无论哪种方式我都需要帮助!
答案 0 :(得分:1)
您可以使用计数和分组。像这样:
SELECT DISTINCT `t_state_id_state`
, `t_state_name_full`
, COUNT(*)
FROM (`t_state`)
LEFT JOIN `t_citystate` ON `t_state_id_state` = `t_citystate_id_state`
LEFT JOIN `t_city` ON `t_citystate_id_state` = `t_city_id_city`
LEFT JOIN `t_zipcodecity` ON `t_city_id_city` = `t_zipcodecity_id_city`
LEFT JOIN `t_location` ON `t_zipcodecity_zipcode` = `t_location_zipcode`
GROUP BY `t_state_id_state` , `t_state_name_full`
ORDER BY `t_state_name_full` asc
答案 1 :(得分:0)
SELECT t_state_id_state
, t_state_name_full
, COUNT(DISTINCT t_location_id_location) AS locations_number
FROM
t_state
LEFT JOIN
t_citystate ON t_state_id_state = t_citystate_id_state
LEFT JOIN
t_city ON t_citystate_id_state = t_city_id_city
LEFT JOIN
t_zipcodecity ON t_city_id_city = t_zipcodecity_id_city
LEFT JOIN
t_location ON t_zipcodecity_zipcode = t_location_zipcode
GROUP BY t_state_id_state
ORDER BY t_state_name_full ASC
答案 2 :(得分:0)
好吧,那看起来很好,我的左连接坏了,我最初试图获得所有状态,这就是我使用它们的原因。但我改变它以使用内连接
SELECT t_state_id_state,
t_state_name_full,
COUNT(DISTINCT t_location_id_location) AS locations_number
FROM t_state
INNER JOIN t_citystate ON t_citystate_id_state = t_state_id_state
INNER JOIN t_city ON t_city_id_city = t_citystate_id_city
INNER JOIN t_zipcodecity ON t_zipcodecity_id_city = t_city_id_city
INNER JOIN t_location ON t_location_zipcode = t_zipcodecity_zipcode
GROUP BY t_state_id_state
ORDER BY t_state_name_full ASC
然后我的结果看起来很棒!