SQL选择id =' x'的所有记录的位置的状态是' y'

时间:2016-12-13 15:15:07

标签: mysql sql

我有一个表incoming,其中包含电子邮件列表及其附件。

我导入每个附件并处理它们,此时该行被标记为5

当单个电子邮件的所有行都标记为5时,我可以移动/删除已正确处理的电子邮件。

但是,我正在努力编写一个SQL查询来选择msg_uid,其中具有相同msg_uid的所有行的状态为5

示例表

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

这不允许我删除电子邮件(其中一些有状态3

但是

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

会很成功。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

此查询将让yoy找到特定STATUS的所有5值为msg_uid的每个结果:

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