检索所有相关数据满足指定条件的行

时间:2013-04-26 14:48:09

标签: mysql sql

我有一个job表和一个visit表。一份工作可以有多次访问。我需要检索所有尚未设置为付费的作业,并将所有作业与该作业集绑定为已完成。

所以基本上我只需要在以下情况下检索作业:

  • 尚未支付(paid = 'N')
  • 与该作业相关的所有访问都设置为完整(status = 2)

显然,执行以下操作无效,因为它会返回job.paid = 'N' and visit.status = '2'

的任何结果
SELECT * 
FROM   job INNER JOIN visit 
       ON job.id = visit.job_id 
WHERE  job.paid = 'N' AND 
       visit.status = 2;

我可以检索结果,并运行其他查询来检查作业的所有访问是否完整,但我想知道是否可以在单个查询中检索数据?

4 个答案:

答案 0 :(得分:1)

SELECT * 
FROM job j 
WHERE j.paid = 'N' AND 
  NOT EXISTS (SELECT 1 FROM visit WHERE job_id = j.id AND visit.status <> 2);

答案 1 :(得分:1)

更新1

SELECT  a.ID  -- <<== add some columns here
FROM    job a INNER JOIN visit b ON a.id = b.job_ID
WHERE   a.paid = 'N'
GROUP   BY a.ID
HAVING  COUNT(DISTINCT b.Status) = 1 AND MAX(b.status) = 2

答案 2 :(得分:1)

SELECT * FROM job WHERE paid = 'N' AND id NOT IN (
SELECT job_id FROM visit WHERE status != 2)

答案 3 :(得分:1)

如果你有可能没有与之相关的任何访问记录的作业,并且你想要仍然返回该作业记录,如果它已经支付='N',那么你将要左JOIN。

SELECT * 
FROM JOB j
LEFT JOIN VISIT v
ON j.id = v.job_id
WHERE j.paid = 'N'
AND j.id NOT IN (SELECT job_id FROM visit WHERE status != 2)