简体   繁体   English

MySQL JOIN需要附加条件

[英]MySQL JOIN Needs Additional Condition

I have two tables, a jobs table and an applicants table. 我有两个表,一个工作表和一个申请人表。 The applicants table has a field containing the position applied to. 申请人表有一个包含应聘职位的字段。 My query seems close, except it's returning only jobs that have been applied to. 我的查询似乎很接近,只是它只返回已应用的作业。 What I want is a display of all active jobs that also has a column to display the number of applicants. 我想要的是所有活动职位的显示,并且还有一列显示申请人数量。 Some jobs have no applicants and those are not captured by my query. 有些职位没有应聘者,而我的查询未涵盖这些职位。

SELECT * , COUNT(*) as total
FROM `job` 
INNER JOIN applicants 
ON applicants.position_id=job.id
WHERE active = 'yes'
GROUP BY position_id
ORDER BY title

You want a left join and other small fixes to the query: 您需要查询的left join和其他小的解决方案:

SELECT j.*, COUNT(a.position_id) as total
FROM `job` j LEFT JOIN
     applicants a
     ON a.position_id = j.id
WHERE j.active = 'yes'
GROUP BY j.id 
ORDER BY j.title;

The changes are: 更改为:

  • Introduced table aliases (makes the query easier to write and to read). 引入了表别名(使查询更易于编写和阅读)。
  • Use the table aliases for all column references. 将表别名用于所有列引用。
  • Changed select to j.* rather than * . select更改为j.*而不是* Only the job information is appropriate because of the group by . 由于group by原因,仅职位信息是合适group by
  • Changed group by to j.id , so it never aggregates by NULL . group by更改为j.id ,因此它永远不会通过NULL聚合。
  • Changed the count() to count matches. 更改了count()以计算匹配项。

As other have mentioned, your join would have to be an outer join. 正如其他人提到的那样,您的联接必须是外部联接。

With your simple query, however, you can easily select from job only and get the application count in the select clause. 但是,通过简单的查询,您可以轻松地仅从作业中进行选择,并在select子句中获取应用程序计数。 So you get the query even more readable. 这样您就可以使查询更具可读性。

select 
  job.*,
  (select count(*) from applicants where position_id = job.id) as total
from job
where active = 'yes'
order by title;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM