[英]mysql : count and inner join in same query
我有三張桌子
users, jobs, proposals
users(id, username, address, email)
jobs(id, title, description, etc)
proposals(id, userid, jobid, date)
用戶可以申請許多職位,並且
單個作業可以被許多用戶應用
提案表存儲有關誰申請了哪個職位的信息
select j.* from proposals p inner join jobs j on p.jobid = j.id where p.userid=$userid
上面的查詢列出了特定用戶應用的所有作業。 現在,我想顯示每項工作有多少人在同一查詢中應用過
我試過了
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
也
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
我知道上述查詢是錯誤的,但這會給您一些想法。
不是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;
由於我沒有數據來測試它,因此它可能無法完美運行,請嘗試使用此方法!
如果要使用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
注意:此查詢的性能可能不會比上一個查詢更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.