我正在尝试创建一个查询,该查询将返回特定公司发布的所有作业,以及应用于此作业的总人数。第一部分工作正常 - 我得到了所有的工作和我需要的一切:
$query = "SELECT *,j.job_id as jid, c.name as city_name ".
"FROM jobs j JOIN areas a ON a.area_id = j.job_area ".
"JOIN positions p ON p.position_id = j.job_position ".
"JOIN fields f ON f.id = j.job_field ".
"JOIN cities c ON j.job_city = c.id ".
"JOIN jobTypes jt ON j.job_type = jt.job_id " .
"JOIN companies comp ON j.job_company = comp.company_id ".
"LEFT JOIN jobApplications ja ON ".
"ja.user_id = '".$_SESSION['user_id']."' AND ".
"j.job_id = ja.job_id WHERE j.job_company='$company_id'";
问题是,我想从jobApplications表中添加每个结果行的作业申请人数...我试图在查询中添加COUNT列,这本身很好用:
SELECT COUNT(*) FROM jobApplications ja WHERE ja.job_id=j.job_id
当添加到第一个大查询时,我甚至无法在语法级别上使其工作,所以我不确定它是否可以正常工作...
我尝试将最后一个查询添加到主查询的选择区域,但我总是在计数查询结束时'ja.job_id = j.job_id'后面出现语法错误...
这甚至可能吗?
我希望问题很明确,我知道这里有很多表...... 感谢您的时间和帮助!
答案 0 :(得分:2)
试试这样:
$query = "SELECT (SELECT COUNT(ja2.job_id) FROM jobApplications ja2 WHERE ja2.job_id=j.job_id group by j.job_id), *,j.job_id as jid, c.name as city_name FROM jobs j JOIN areas a ON a.area_id = j.job_area" .
" JOIN positions p ON p.position_id = j.job_position JOIN fields f ON f.id = j.job_field "
." JOIN cities c ON j.job_city = c.id JOIN jobTypes jt ON j.job_type = jt.job_id " .
"JOIN companies comp ON j.job_company = comp.company_id LEFT JOIN jobApplications ja ON ja.user_id = '".$_SESSION['user_id']."' AND j.job_id = ja.job_id WHERE j.job_company='$company_id'";
答案 1 :(得分:2)
我不知道你的PK应用程序,但这可能有效。
$query = "SELECT *,j.job_id as jid, c.name as city_name, COUNT(ja.<primary key>) ".
"FROM jobs j JOIN areas a ON a.area_id = j.job_area ".
"JOIN positions p ON p.position_id = j.job_position ".
"JOIN fields f ON f.id = j.job_field ".
"JOIN cities c ON j.job_city = c.id ".
"JOIN jobTypes jt ON j.job_type = jt.job_id " .
"JOIN companies comp ON j.job_company = comp.company_id ".
"LEFT JOIN jobApplications ja ON ".
"ja.user_id = '".$_SESSION['user_id']."' AND ".
"j.job_id = ja.job_id WHERE j.job_company='$company_id' ".
"GROUP By jid";
答案 2 :(得分:2)
您必须使用GROUP
SELECT *,j.job_id as jid, c.name as city_name, COUNT(jobApplications.*)
FROM jobs j JOIN areas a ON a.area_id = j.job_area
JOIN positions p ON p.position_id = j.job_position
JOIN fields f ON f.id = j.job_field
JOIN cities c ON j.job_city = c.id
JOIN jobTypes jt ON j.job_type = jt.job_id
JOIN companies comp ON j.job_company = comp.company_id
LEFT JOIN jobApplications ja ON
ja.user_id = '".$_SESSION['user_id']."' AND
j.job_id = ja.job_id WHERE j.job_company='$company_id'
GROUP BY jid
希望有所帮助:)