gpt4 book ai didi

MySQL查询多count语句的有效方法

转载 作者:行者123 更新时间:2023-11-29 18:16:56 24 4
gpt4 key购买 nike

让我们有 4 个简单的表格:

TABLE region (id, name)
TABLE country (id, name, region_id)
TABLE organization (id, name, country_id)
TABLE person (id, name, organization_id)

我想进行查询,我可以:

  • 区域名称
  • 各地区的人数
  • 国家/地区名称
  • 各个国家/地区的人数
  • 组织名称
  • 组织人数
  • 人名

例如:欧洲,20,斯洛伐克,2,生命大学,1,某人

如何在 MySQL 中有效地进行这些计数?

我有一个巨大的查询,其中每个计数都有内联选择,但这根本没有效率。我正在考虑案例求和,但如果我有数千个不同名称的组织,我不太理解这个概念......

最佳答案

 SELECT r.name as region, count(DISTINCT r.id) as region_total,
c.name as city, count(DISTINCT c.id) as country_total,
o.name as organization, count(DISTINCT o.id) as organization_total,
COUNT(p.id) as person_total
FROM region r
JOIN country c
on r.id= c.region_id
JOIN organization o
ON c.id = o.country_id
JOIN person p
ON o.id p.organization_id
GROUP BY r.id, c.id, o.id
ORDER BY r.id, c.id, o.id

我不明白你想如何在此处包含人名

关于MySQL查询多count语句的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46938310/

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