Mysql 从3个表中获取空记录
我有三张桌子看起来像 表1各栏: 身份证件 产品 表2列: 身份证件 表1\u id 模型 表3列:id、表2\U id、销售人员 可以看出,表1与表2的连接是一对多,表2与表3的连接也是一对多。 我需要得到没有销售人员的产品。Mysql 从3个表中获取空记录,mysql,sql,Mysql,Sql,我有三张桌子看起来像 表1各栏: 身份证件 产品 表2列: 身份证件 表1\u id 模型 表3列:id、表2\U id、销售人员 可以看出,表1与表2的连接是一对多,表2与表3的连接也是一对多。 我需要得到没有销售人员的产品。 我试图检查模型销售员是否为空,但如果一个模型有销售员,而另一个模型没有相同产品的销售员,它仍然会显示在结果中。这将返回其任何模型都没有销售员的产品。这也会返回没有型号的产品 select p.id, p.product from table1 p where
我试图检查模型销售员是否为空,但如果一个模型有销售员,而另一个模型没有相同产品的销售员,它仍然会显示在结果中。这将返回其任何模型都没有销售员的产品。这也会返回没有型号的产品
select
p.id, p.product
from
table1 p
where
p.id not in (
select
m.table_1_id
from
table2 m
inner join table3 s on s.table_2_id = m.id)
您也可以使用(not)exists
,而不是(not)in
。下面我使用这两种方法,只返回有型号但没有销售人员的产品
select
p.id, p.product
from
table1 p
where
exists (
select 'x'
from table2 m
where m.table_1_id = p.id) and
p.id not in (
select
m.table_1_id
from
table2 m
inner join table3 s on s.table_2_id = m.id)
或者,您也可以显示模型:
select
p.id as productid,
p.product,
m.id as modelid,
m.model
from
table1 p
inner join table2 m on m.table_1_id = p.id
where
not exists (
select 'x'
from table3 s
where s.table_2_id = m.id)
有时使用/滥用左连接而不是exists。我认为它的可读性较差,但有时速度更快(也可能较慢!)
如果我理解您的要求,请考虑计数并检查结果,如果0可以:-
SELECT a.id, a.product, COUNT(c.id) AS salesman_count
FROM table_1 a
LEFT OUTER JOIN table_2 b ON a.id = b.table_1_id
LEFT OUTER JOIN table_3 c ON b.id = c.table_2_id
GROUP BY a.id, a.product
HAVING salesman_count = 0
请发布您的SQL。另请参阅
SELECT a.id, a.product, COUNT(c.id) AS salesman_count
FROM table_1 a
LEFT OUTER JOIN table_2 b ON a.id = b.table_1_id
LEFT OUTER JOIN table_3 c ON b.id = c.table_2_id
GROUP BY a.id, a.product
HAVING salesman_count = 0