Mysql 查询具有多个状态的条目

Mysql query to with multiple entires with status

我们有一个 table,其中 order_id 是根据为其设置的状态多次出现

+-------+------------+-----------------+---------------------+
| id    | order_id   | status          | created_at          |
+-------+------------+-----------------+---------------------+
| 32621 | 0000000881 | AUTHORISED      | 2018-08-06 16:17:38 |
| 32622 | 0000000881 | AUTHORISED      | 2018-08-06 16:46:29 |
| 32623 | 0000000881 | REFUSED         | 2018-08-06 17:18:33 |
| 32624 | 0000000881 | CAPTURED        | 2018-08-06 17:54:10 |
| 32625 | 0000000881 | CAPTURED        | 2018-08-06 18:33:47 |
| 32626 | 0000000882 | REFUSED         | 2018-08-06 19:17:44 |
| 32627 | 0000000882 | AUTHORISED      | 2018-08-06 20:06:25 |
| 32628 | 0000000882 | CAPTURED        | 2018-08-06 21:00:13 |
| 32629 | 0000000883 | REFUSED         | 2018-08-06 21:59:48 |
| 32630 | 0000000883 | CAPTURED        | 2018-08-06 23:05:40 |

我们目前正在查找未设置授权状态的 order_id。

任何建议都将不胜感激,因为我们对这些查询的了解很少。

谢谢

我会使用 WHERE NOT EXISTS 子句来查找 order_id 值,其中 AUTHORISED 不存在。

SELECT DISTINCT
 order_id
FROM yourTable AS t
WHERE NOT EXISTS
 (
  SELECT 1
  FROM yourTable AS t2
  WHERE t.order_id = t2.order_id
    AND t2.status = 'AUTHORISED'
 );

我会使用子句来查找 order_id 值,其中 AUTHORISED 不存在。

SELECT order_id
FROM table t
GROUP BY order_id
HAVING SUM(status = 'AUTHORISED') = 0;

做聚合:

SELECT order_id
FROM table t
GROUP BY order_id
HAVING SUM(status = 'AUTHORISED') = 0;