Mysql 获取特定类别中没有任何产品的类别

Mysql 获取特定类别中没有任何产品的类别,mysql,sql,Mysql,Sql,我正在尝试编写一个sql查询,以获取没有来自特定类别的任何产品的类别。假设我有a,b,c,d,e类,每个类都有一些产品。现在我需要得到所有不包括a类产品的类别 类别表: id name 1 A 2 B 3 C 4 D 5 E 类别产品表: product_id category_id 1 1 1 2 2 3 2 1 4 3 3 2 3

我正在尝试编写一个sql查询,以获取没有来自特定类别的任何产品的类别。假设我有a,b,c,d,e类,每个类都有一些产品。现在我需要得到所有不包括a类产品的类别

类别表:

id  name
1   A
2   B
3   C
4   D
5   E
类别产品表:

product_id   category_id
1            1
1            2
2            3
2            1
4            3
3            2
3            4
3            5
4            5
下面是我使用的查询,它给出了B,C,D,E(不是预期的)


但是我需要的结果是D类,E类,它们没有来自A类的任何产品。

您应该使用内部联接

  select distinct  t2.name
  from category_products t1 
  inner join Categories t2 on t2.id = t1.category_id
  where t1.product_id not in 
   (select p.product_id
   from category_products p
   inner join Categories c on c.id = p.category_id
   where c.name ='A') 

你应该使用内部连接

  select distinct  t2.name
  from category_products t1 
  inner join Categories t2 on t2.id = t1.category_id
  where t1.product_id not in 
   (select p.product_id
   from category_products p
   inner join Categories c on c.id = p.category_id
   where c.name ='A') 

我倾向于使用
groupby
have

select pc.product_id
from category_products pc join
     categories c
     on c.id = pc.category_id
group by pc.product_id
having sum(c.name = 'A') = 0;

我倾向于使用
groupby
have

select pc.product_id
from category_products pc join
     categories c
     on c.id = pc.category_id
group by pc.product_id
having sum(c.name = 'A') = 0;

您需要再进行一次内部查询,例如:

SELECT name
FROM categories 
where id NOT IN (
    SELECT DISTINCT category_id 
    FROM category_products WHERE 
    product_id IN (
        SELECT product_id FROM category_products WHERE category_id = 1
    )
);
这将返回D和E


以下是您需要执行的另一个内部查询,例如:

SELECT name
FROM categories 
where id NOT IN (
    SELECT DISTINCT category_id 
    FROM category_products WHERE 
    product_id IN (
        SELECT product_id FROM category_products WHERE category_id = 1
    )
);
这将返回D和E


以下是你问的不清楚的问题。你期望的结果是什么?@AlvinThompson期望的结果是D类和E类,它们没有任何A类产品。你问的不清楚。你期望的结果是什么?@AlvinThompson期望的结果是D类和E类,它们没有任何A类产品。谢谢你的回答,但它给出的结果是B、C、D、E。谢谢你的回答,但它给出的结果是B、C、D、E。