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 ?
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.