简体   繁体   中英

SQL select where ALL records of id = 'x' have status of 'y'

I have a single table incoming which contains a list of emails , and their attachments.

I import each of the attachements, and process them, at which point that row gets marked as 5

When all rows of an individual email are marked as 5, I can then move/delete the email as it has been processed correctly.

However, I'm struggling to write a SQL query which is to select the msg_uid where ALL rows with the same msg_uid have a status of 5

Example table

 -----------------------------------------------------
 | id | STATUS | i2d_id | msg_uid | i2d_msg          |
 -----------------------------------------------------
 | 16 | 5      | 98390  | 53      | Result is ready. |
 -----------------------------------------------------
 | 17 | 3      | 98391  | 53      | Result is ready. |
 -----------------------------------------------------
 | 18 | 5      | 98392  | 53      | Result is ready. |
 -----------------------------------------------------
 | 19 | 3      | 98393  | 53      | Result is ready. |
 -----------------------------------------------------
 | 20 | 5      | 98394  | 53      | Result is ready. |
 -----------------------------------------------------

This would not allow me to remove the email (some have status 3

But

-----------------------------------------------------
| id | STATUS | i2d_id | msg_uid | i2d_msg          |
-----------------------------------------------------
| 16 | 5      | 98390  | 53      | Result is ready. |
-----------------------------------------------------
| 17 | 5      | 98391  | 53      | Result is ready. |
-----------------------------------------------------
| 18 | 5      | 98392  | 53      | Result is ready. |
-----------------------------------------------------
| 19 | 5      | 98393  | 53      | Result is ready. |
-----------------------------------------------------
| 20 | 5      | 98394  | 53      | Result is ready. |
-----------------------------------------------------

Would be a success.

 SELECT msg_uid 
 FROM yourTable
 GROUP BY msg_uid 
 HAVING COUNT(*) = COUNT(CASE WHEN STATUS = 5 THEN 1 END)

This query will let yoy find every result where all of the STATUS values are 5 for a particular msg_uid :

SELECT *
FROM incoming i
WHERE NOT EXISTS(SELECT 1 FROM incoming
                 WHERE msg_uid = i.msg_uid
                 AND `status` <> 5);

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