1
select colA, colB from car
where car.id in (select id from make) and 
car.id in (select id from model);

上面的查询按原样完美地工作,假设有一种情况是 make 表没有被任何东西填充。只是一张空桌子。有没有办法让连接不在该表上发生?

基本上,如果表有 1 行或更多行,则应用 where 条件。否则,忽略它,不要限制它。

有没有办法在左连接上实现相同的结果?

编辑

结果算法:

  • 从原桌车中选择东西。
  • 如果 make 有任何内容,则带走任何不在 table make 中的东西
  • 如果模型有任何内容,则带走任何不在表格模型中的东西......
  • 如果 model2 有任何内容,则删除 table model2 中的任何内容....

thisnk of model2 是我不想要的东西的表格,以及我想要的东西的模型和制作表格。

4

3 回答 3

2
SELECT colA, colB
FROM car
WHERE ((SELECT COUNT(*) FROM make) = 0) OR id IN (SELECT id FROM make))
  AND id IN (SELECT id from model)

左连接:

SELECT DISTINCT colA, colB
FROM car
JOIN (SELECT COUNT(*) c FROM make) mcount
LEFT JOIN make ON car.id = make.id
JOIN model ON car.id = model.id
WHERE mcount.c = 0 OR make.id IS NOT NULL

usingOR通常可以防止使用索引,因此使用 UNION 可能会更好:

SELECT distinct colA, colB
FROM car
JOIN make on car.id = make.id
JOIN model on car.id = model.id

UNION

SELECT distinct colA, colB
FROM car
JOIN (SELECT COUNT(*) c FROM make) make
JOIN model ON car.id = model.id
WHERE make.c = 0

将版本扩展LEFT JOIN到两个表很简单:

SELECT DISTINCT colA, colB
FROM car
JOIN (SELECT COUNT(*) c FROM make) makecount
LEFT JOIN make ON car.id = make.id
JOIN (SELECT COUNT(*) c FROM model) modelcount
LEFT JOIN model ON car.id = model.id
WHERE (makecount.c = 0 OR make.id IS NOT NULL)
  AND (modelcount.c = 0 OR model.id IS NOT NULL)

如果还有其他表要加入,您可以继续重复此模式。

使用 UNION 查询更难做到这一点,因为您需要为每个可以为空的连接表组合创建一个子查询:一个子查询用于两者makemodel具有行,一个用于 just make,一个用于 just model,一个用于两者都为空。如果有 3 个表正在连接,这将扩展为 8 个子查询(即总是有 2 n个子查询)。也许有人可以想出一个更好的方法,我想不出它。

于 2013-07-11T00:51:26.673 回答
1

您必须使用更复杂的连接来执行此操作:

select c.colA, c.colB
from car c cross join
     (select count(*) as num from make) m
where num = 0 or
      (c.id in (select id from make) and 
       c.id in (select id from model)
      )
于 2013-07-11T00:51:17.773 回答
1

尝试这个

     select colA, colB from car
     left join make on make.id = car.id
     inner join model on model.id = car.is
     where make.id IS NOT NULL
于 2013-07-11T00:53:03.823 回答