如果WHERE子句适用于多行,是否所有行都经过测试?

时间:2014-07-16 04:12:52

标签: mysql

我有一个包含项目和作业的数据库。每个作业都链接到一个项目,但项目可以有多个作业。如何选择所有未归档但其关联分配都具有特定状态(付费)的项目?以下结果产生了预期的结果,因为我目前没有具有多个任务的项目,但是如果我这样做会有效吗?

SELECT projects.*
FROM projects,
     assignments
WHERE projects.id=assignments.project_id
  AND assignments.status='Paid'
  AND projects.archived='N'

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT p.*
FROM projects p
WHERE NOT EXISTS
(SELECT 1
 FROM assignments a
 WHERE p.id = a.project_id AND a.status <> 'Paid'
)
AND p.archived='N';

SQL Fiddle demo

答案 1 :(得分:0)

尝试LEFT JOIN可能你想要这个

SELECT projects.*
FROM projects LEFT JOIN assignments
ON projects.id=assignments.project_id
WHERE assignments.status='Paid'
  AND projects.archived='N'

答案 2 :(得分:0)

SELECT *
FROM projects WHERE projects.archived='N' AND projects.id IN(
SELECT s.id FROM projects p,assignments s WHERE p.id=s.id
AND s.status='Paid');

试试这个可行。