简体   繁体   English

mysql:计数和内部联接在同一查询中

[英]mysql : count and inner join in same query

I have three tables 我有三张桌子

users, jobs, proposals

users(id, username, address, email)

jobs(id, title, description, etc)

proposals(id, userid, jobid, date)

A users can apply to many jobs and 用户可以申请许多职位,并且

a single job can be applied by many users 单个作业可以被许多用户应用

proposals table stores information of who applied to which job 提案表存储有关谁申请了哪个职位的信息

select j.* from proposals p inner join jobs j on p.jobid = j.id where p.userid=$userid

The above query lists all the jobs applied by the specific user. 上面的查询列出了特定用户应用的所有作业。 Now I want to show for each job how many people have applied in same query, is it possible 现在,我想显示每项工作有多少人在同一查询中应用过

I tried 我试过了

 select j.*, count(select * from proposals where jobid =j.id) as count from proposals p inner join jobs j on p.jobid = j.id where p.userid=$userid

also

select j.*, (select count(*) from proposals where jobid =j.id) as count from proposals p inner join jobs j on p.jobid = j.id where p.userid=$userid 

I know the above queries is wrong but this will give some idea. 我知道上述查询是错误的,但这会给您一些想法。

Isn't group by what you are searching for ? 不是group by您要搜索group by内容group by

select j.title, count(*) as number_of_applicants 
from jobs j join proposals 
on j.id = p.jobid 
group by p.jobid;

It might not work perfectly since I don't have the datas to test it, but try on this path ! 由于我没有数据来测试它,因此它可能无法完美运行,请尝试使用此方法!

If you want to use group by , also a subquery is necessary, try following: 如果要使用group by ,则还需要一个子查询,请尝试以下操作:

select j.*, t.cnt
from jobs j 
join proposals p on p.jobid = j.id
left join (
    select jobid, count(userid) as cnt
    from proposals
    group by jobid
) t on t.jobid = j.id 
where p.userid = $userid

Note: This query may not have better performance than your last query. 注意:此查询的性能可能不会比上一个查询更好。

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

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