连接查询中的 MySQL 条件字段

标签 mysql sql join conditional-statements

我在向查询中添加条件字段时遇到问题。 查询返回在我的网站上发布的职位(很多加入,没什么特别的)。问题是我需要添加另一个字段才能知道当前用户是否已经申请了这份工作(以便删除申请按钮)...

我有一个 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"

我为添加条件选择所做的任何尝试都破坏了查询,是否有人可以给我更好的指导?

谢谢!!

最佳答案

如果不了解更多关于您的模式的信息,很难肯定地说,但您在左连接的正确轨道上。您需要使用当前用户的申请人 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"

关于连接查询中的 MySQL 条件字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8433167/

相关文章:

mysql - 按索引使用排序

mysql - SQL 语法错误/无法添加或更新子行

mysql - 数据库问题 : Change Simple Relational Tables to Non-Relational?

SQL 规范化现有(多对多)数据

mysql - 选择没有任何特定 Bar 事件的 Foo 对象

MySQL 连接 2 个表

php - codeigniter,使用 Case When 进行Where 查询

MySQL简单的select语句,如果行值与前一个值不同则创建自动增量

mysql - 用 0 填充缺失值 - sql 查询

java - 在 Hadoop map-reduce 中对连接的数据进行分组