从3个表中获取空记录

时间:2014-05-15 08:04:28

标签: mysql sql

我有3张看起来像

的桌子

表1列: ID, 产品

表2列: ID, table_1_id 模型

表3列:id,table_2_id,salesman

可以看出,表一被连接到表二乘一对多,并且表二连接到表三乘一对多。 我需要得到没有任何推销员的产品。 我试图检查模型推销员是否为空,但如果一个模型有推销员而其他模型没有相同的产品,它仍会显示在结果中。

2 个答案:

答案 0 :(得分:2)

这将返回对于任何型号都没有任何推销员的产品。这也会返回没有模型的产品。

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

有时会使用/滥用左连接,而不是存在。我认为它的可读性较差,但有时它更快(也可能更慢!)。

{{1}}

答案 1 :(得分:0)

如果我理解了您的要求,请考虑使用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