mysql - 根据给定表中的外键查找多个表中的行数
问题描述
我有一个数据库,其中包含我关心的以下表格。
- JobAreas(我要查询其他表的基表)
- JobSkills(每个工作技能通过外键即 parent_id 属于一个工作区域)
- 工作(每个工作必须通过外键即 category_id 属于一个工作区域)
- UserSkills(此表包含与 Job Area 相关的 JobSkill)
我正在附加表格结构。
我正在尝试创建一个 SQL 查询,它可以为我提供各种工作领域的技能数量、工作数量和人数。尽管计算在特定工作区域提供服务的用户似乎很困难,因为它是间接连接的。我尝试使用以下查询获取所有工作领域的技能数量和工作数量。
select
t.id,
t.title,
count(s.parent_id) as skillsCount,
count(m.category_id) as jobCount
from
job_areas t
left join skill_types s ON s.parent_id = t.id
left join job_requests m ON m.category_id = t.id
group by
t.id
但它没有给出正确的数据。有人可以指导我如何实现这一目标。
解决方案
You are joining along different dimensions. The quick-and-dirty way to fix this is to use count(distinct)
:
select t.id, t.title,
count(distinct s.parent_id) as skillsCount,
count(distinct m.category_id) as jobCount
from job_areas t left join
skill_types s
ON s.parent_id = t.id left join
job_requests m
ON m.category_id = t.id
group by t.id;
This works fine if there are just a handful of skills and categories for each job. If there are many, you want to pre-aggregate before the join
or use correlated subqueries.
推荐阅读
- java - Fedora linux 上的“JAVA_HOME 设置为无效目录”gradlew 错误
- tensorflow - 即使使用 pip 安装后也没有名为 tensorflow 的模块
- angular - 如何正确使用 dotdotdot 在 Angular 5 中溢出文本?
- javascript - 如何通过nodejs发送加密消息?
- android - ListView/RecyclerView 虚拟化
- javascript - 将上传的文件图片添加到 json 文件中
- spring-boot - 在 SpringBoot 中使用 Mockmvc perform() 方法调用 RestController 时出现空指针异常
- javascript - 在nestjs的过滤器中注入服务
- python - 不同的结果响应scrapy shell
- python - statistics.mean() vs sum()/len() vs np.average() 用于列表列表