MySql Databe - 列出只有一个类别的产品

MySql Databe - listing products that have only one category

我在数据库中有 table,例如:

===========================
products_id | categories_id
===========================
      1            2
      1            1
      1            3
      1            4
      1            5
      2            5
      2            2
      2            3
      2            4
      3            5
      4            5
      5            5 
===========================

我在 mysql 方面不太好,所以我需要一些帮助来解决这个问题。我想列出所有只有 categories_id = 5products_id。也就是说,即使 categories_id 为 5,也只有在不存在包含该 products_id 和不同的 categories_id 的其他行时才应列出它。 所以输出应该是:3 4 5.

这是一种使用 having 子句进行聚合和过滤的方法:

select product_id
from mytable
group by product_id
having min(category_id) = 5 and max(category_id) = min(category_id)