MySQL-如果条件不唯一,则丢弃记录

时间:2018-07-02 00:41:46

标签: mysql

我正在尝试构建此查询,我认为在不使用子查询的情况下对其进行优化会有些复杂。

| baggage_id | checkpoint | status |
|------------|------------|--------|
| 1          | 3          | 1      |
| 2          | 3          | 1      |
| 2          | 5          | 1      |
| 3          | 3          | 0      |
| 4          | 3          | 1      |
| 5          | 3          | 1      |
| 6          | 3          | 0      |

应该返回

| baggage_id | checkpoint | status |
|------------|------------|--------|
| 1          | 3          | 1      |
| 4          | 3          | 1      |
| 5          | 3          | 1      |

我只需要bagagges_id,

  • 检查点= 3
  • 状态= 1
  • 没有检查点= 5 AND状态= 1的baggage_id

有人可以帮我吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

一种方法是左联接在集合上具有折叠以排除。

SELECT *
FROM bags b
LEFT JOIN (
   -- Find set of baggage_id's to exclude
   -- The group-by is to collapse the set to distinct baggage ID's
   -- to avoid increasing multiplicity.
   SELECT baggage_id, 1 as hasCheckpoint5AndStatus1
   FROM bags
   WHERE checkpoint = 5 AND status = 1
   GROUP BY baggage_id
) b2
ON b.baggage_id = b2.baggage_id
WHERE b.checkpoint = 3 AND b.status = 1
-- If NULL, then baggage_id is NOT excluded
AND b2.hasCheckpoint5AndStatus1 IS NULL