简体   繁体   中英

SQL: find all items on left side where right side items all have specific field value

There is a table job that contains data as shown below:

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

There is a table item that contains data as shown below:

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

I want to run a query, that will return all Jobs whose "children" all have a status of X

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

That should return

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

Because all of Job 2 items have status = PROCESSED . Job 1 does not appear because it has items with the unwanted status NEW

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

这将返回ID并非由状态不同于“ PROCESSED”的所有Jobid导致的Job的全部。

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';

Or

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';   

SQL Fiddle

MySQL 5.5.32 Schema Setup :

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)
;

Query 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 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM