【发布时间】:2014-05-15 08:04:28
【问题描述】:
我有 3 张桌子,看起来像
表 1 列: ID, 产品
表 2 列: ID, table_1_id 型号
表 3 列:id、table_2_id、salesman
可以看出,表一与表二是一对多的连接,表二也是与表三的一对多连接。 我需要得到没有任何推销员的产品。 我尝试检查模型推销员是否为空,但如果一个模型有推销员,而另一个模型没有推销员,它仍然会显示在结果中。
【问题讨论】:
我有 3 张桌子,看起来像
表 1 列: ID, 产品
表 2 列: ID, table_1_id 型号
表 3 列:id、table_2_id、salesman
可以看出,表一与表二是一对多的连接,表二也是与表三的一对多连接。 我需要得到没有任何推销员的产品。 我尝试检查模型推销员是否为空,但如果一个模型有推销员,而另一个模型没有推销员,它仍然会显示在结果中。
【问题讨论】:
这将返回没有任何型号的推销员的产品。这也会返回没有模型的产品。
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) in,您还可以使用(not) exists。下面我同时使用两者,只退回有型号但没有销售员的产品。
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)
有时使用/滥用左连接而不是存在。我认为它的可读性较差,但有时它更快(也可能更慢!)。
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
left join table3 s on s.table_2_id = m.id
where
s.id is null
【讨论】:
如果我理解您的要求,请考虑 COUNT 并检查结果,如果 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
【讨论】: