连接查询中的MySQL条件字段

时间:2011-12-08 15:14:30

标签: mysql sql join conditional

我在向查询添加条件字段时遇到问题。 该查询返回在我的网站上发布的作业(许多连接,没有什么特别的)。问题是我需要添加另一个字段才能知道当前用户是否已经申请了这个工作(为了删除APPLY按钮)......

我有一个jobApplication表,它有user_id和job_id表。我想过使用另一个连接,但这不起作用。我尝试使用IF和SELECT创建它,但没有完全成功地使它工作:/ ...

这是我的疑问:

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 <missing>
WHERE j.job_field = '$field' AND j.job_position = '$position' 
  AND j.job_area = '$area' 
ORDER BY j.creationDate DESC"

我添加条件选择的任何尝试都打破了查询,有人可以给我一个更好的方向吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

如果不了解更多关于您的架构的话,很难肯定地说,但是您在左侧连接的正确轨道上。您需要使用当前用户的申请人ID和职位表中的职位ID将申请表连接到申请人表格。

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.applicantId = '$applicantId' and ja.jobId = j.jobId
WHERE 
 j.job_field = '$field' 
AND j.job_position = '$position' 
AND j.job_area = '$area' 
ORDER BY j.creationDate DESC"