MYSQL查询更多条件

时间:2016-08-26 02:31:41

标签: mysql

我的SQL查询有问题。 我有工作表和job_feature。现在每个Job对象都有许多功能

示例:作业1具有功能1,2,9。 所以我现在需要这个查询:Select job has feature (1 or 2) and 9.高级。 Select job has feature (1 or 2 or 3) and (9 or 10)和...... 如果使用此查询

SELECT * 
FROM `m_job` as job
JOIN `d_job_feature` as jf ON job.id= jf.job_id
WHERE (jf.feature_id = 1 OR jf.feature_id = 2)
AND jf.feature_id = 9;

=>返回空数据

现在,我如何使用SQL查询此数据。 谢谢!

2 个答案:

答案 0 :(得分:2)

您的查询存在的问题是,feature_id对于给定的行不能等于1或2以及9.您需要使用group by对要素进行分组。然后,您可以使用condition aggregation查看给定功能是否可以存在这两个条件。

这是使用exists的一个选项:

select *
from m_job as m
where exists (
    select 1
    from d_job_feature as d
    where m.id=d.job_id
    group by d.job_id
    having max(case when d.feature_id in (1,2,3) then 1 else 0 end) = 1 and 
           max(case when d.feature_id in (9,10) then 1 else 0 end) = 1 
)

答案 1 :(得分:1)

如果您加入两个查询怎么办?

SELECT * 
FROM (
   SElECT`m_job` as job
JOIN `d_job_feature` as jf ON job.id= jf.job_id
WHERE jf.feature_id in(1,2,3)
) as t1 INNER JOIN
(
SELECT job.id
FROM `m_job` as job
JOIN `d_job_feature` as jf ON job.id= jf.job_id
WHERE jf.feature_id IN (9,10)
) as t2 ON t2.id ==t1.id