SQL 查询只有一个关联项的多对多关联 table

SQL query many-to-many association table that have only one single associated item

我在下方有促销类别 table;

+----+--------------+-------------+
| id | promotion_id | category_id |
+----+--------------+-------------+
|  1 |            1 |           1 |
|  2 |            2 |           1 |
|  3 |            2 |           2 |
|  4 |            3 |           1 |
|  5 |            4 |           2 |
|  6 |            4 |           3 |
|  7 |            5 |           2 |
+----+--------------+-------------+

我不知道如何查询类似

Any promotion that have only one category and it is category_id = 1

期望结果 id 1, 4 其中有 promotion_id 1,3 只有一个 category_id = 1

我们可以在这里使用聚合:

SELECT promotion_id
FROM yourTable
GROUP BY promotion_id
HAVING MIN(category_id) = MAX(category_id) AND  -- only one category
       MIN(category_id) = 1;                    -- that category is 1