SQL:查找左侧所有具有特定字段值的项目

时间:2014-12-04 18:45:30

标签: mysql sql

表格job包含如下所示的数据:

Id   Status
-----------
1    NEW
2    NEW

表格item包含如下所示的数据:

Id   Status   JobId
---------------------
1    NEW        1
2    PROCESSED  1
3    NEW        1
4    PROCESSED  2
5    PROCESSED  2

我想运行一个查询,它将返回所有“子”都具有X

状态的作业

伪SQL: SELECT * FROM Job WHERE status = 'NEW' AND Items for Job WHERE all items status = PROCESSED

那应该返回

Id   Status
-----------
2    NEW

因为所有Job 2项都有status = PROCESSED。 作业1未显示,因为它包含不需要的状态NEW

3 个答案:

答案 0 :(得分:1)

SELECT * from job where Id not in (SELECT JobId from item where Status <> 'PROCESSED');

这将从作业中返回所有内容,而该作业不属于所有状态不同于&#39; PROCESSED&#39;

的作业者。

答案 1 :(得分:0)

SELECT j.* FROM Job j
WHERE not exists (select 1 from item i where i.JobId = j.id and i.Status != 'PROCESSED')
  and exists (select 1 from item i where i.JobId = j.id and i.Status = 'PROCESSED')
  and j.status = 'NEW';

或者

SELECT j.* FROM Job j
WHERE j.id in 
    (select jobId from ( 
        select jobId, count(distinct status) n_all, 
        count(distinct case when status = 'PROCESSED' 
                       then status else null 
                       end) n_processed
        from item group by jobId
        ) t
     where n_all = n_processed
    )
and j.status = 'NEW';   

答案 2 :(得分:0)

SQL Fiddle

MySQL 5.5.32架构设置

CREATE TABLE job
    (`Id` int, `Status` varchar(3))
;

INSERT INTO job
    (`Id`, `Status`)
VALUES
    (1, 'NEW'),
    (2, 'NEW')
;

CREATE TABLE item
    (`Id` int, `Status` varchar(9), `JobId` int)
;

INSERT INTO item
    (`Id`, `Status`, `JobId`)
VALUES
    (1, 'NEW', 1),
    (2, 'PROCESSED', 1),
    (3, 'NEW', 1),
    (4, 'PROCESSED', 2),
    (5, 'PROCESSED', 2)
;

查询1

SELECT *
FROM job
WHERE NOT EXISTS
      (SELECT 1
       FROM item
       WHERE job.Id = item.JobId AND item.Status <> 'PROCESSED')

<强> Results

| ID | STATUS |
|----|--------|
|  2 |    NEW |