3

我有一张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

4 回答 4

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);
于 2013-04-26T14:51:39.420 回答
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
于 2013-04-26T14:51:59.907 回答
1
SELECT * FROM job WHERE paid = 'N' AND id NOT IN (
SELECT job_id FROM visit WHERE status != 2)
于 2013-04-26T14:53:31.757 回答
1

如果您可能有一个没有任何访问记录与之关联的工作,并且如果它已支付 = 'N',您仍然希望返回该工作记录,那么您将需要 LEFT 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)
于 2013-04-26T14:53:48.183 回答