gpt4 book ai didi

mysql连接和计数

转载 作者:可可西里 更新时间:2023-11-01 08:53:15 25 4
gpt4 key购买 nike

以某种方式未能成功创建我想要的查询。

DB是跟locations有关的,相关的有下表

  • t_location - 位置列表,包括。字段 t_location_zipcodet_location_id_location
  • t_zipcodecity - 仅连接表 t_zipcodecity_zipcode t_zipcodecity_id_city
  • t_city - 包含 t_city_id_city
  • 的城市列表
  • t_citystate - 连接表,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 ­

效果很好。

现在我还需要/想要的是获得每个州的位置数量,但我却惨遭失败。我不知道是否可以在这个查询中完成,或者我是否需要另一个查询,无论哪种方式我都需要帮助!

最佳答案

您可以使用计数和分组依据。像这样:

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

关于mysql连接和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9386921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com