首页 > 解决方案 > 根据给定表中的外键查找多个表中的行数

问题描述

我有一个数据库,其中包含我关心的以下表格。

  1. JobAreas(我要查询其他表的基表)
  2. JobSkills(每个工作技能通过外键即 parent_id 属于一个工作区域)
  3. 工作(每个工作必须通过外键即 category_id 属于一个工作区域)
  4. 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

但它没有给出正确的数据。有人可以指导我如何实现这一目标。

在此处输入图像描述

标签: mysqlsqljoin

解决方案


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.


推荐阅读