MYSQL 如何检查是否有除值 x 以外的多行

MYSQL how to check if there are multiple rows other than value x

我有一个映射 table 可以将某些 ID 映射到彼此(产品和类别)。现在我需要检查这个映射类别中是否有多行。例如,每个产品都有一个类别 ID 为 1 的标准映射。现在可能有更多行具有其他类别 ID。例如:

Product_id  Category_id
1           1
1           2
2           1
3           1 
4           1
4           2

我只需要 select 那些只有产品 ID 和类别 ID 为 1 的行。所以在这种情况下,我想选择 ID 为 2,3 的产品。因为1和4有多个类别id。

我有这个查询(这是一个连接,因为我想在此查询中添加一些其他数据):

SELECT * FROM `products` as P
LEFT JOIN `product_categories` as PC
ON PC.`product_id` = P.`product_id`
WHERE PC.`category_id` = 1 AND 
LIMIT 10

现在我不知道我需要在 Where 语句中做什么。谁能帮帮我?

我考虑过使用计数,但我认为这不是最佳解决方案。也许检查类别 id 中是否有除 1 以外的其他值或其他值?

我考虑了你的table作为参考。您可以在之后添加或执行加入。

这里不能添加where。计数是一个组函数(也称为聚合函数)。所以你必须添加 having 而不是 where.

正在创建 table:

CREATE TABLE IF NOT EXISTS `test` (
  `product_id` int(6) unsigned NOT NULL,
  `category_id` int(6) unsigned NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `test` (`product_id`, `category_id`) VALUES
(1,1),
(1,2),
(2,1),
(3,1), 
(4,1),
(4,2)

生成结果SQL:

select product_id,category_id 
from test group by product_id having count(product_id)<2

输出:

product_id  category_id
----------  ------------
     2           1
     3           1