sql中的条件Where子句

时间:2013-07-11 00:46:54

标签: mysql sql left-join

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

上面的查询工作原理完全正确,比如说有一种情况是make表没有被任何东西填充。只是一张空桌子。有没有办法让连接不在那张桌子上?

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

有没有办法在左连接上获得相同的结果?

修改

结果算法:

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

模型2的Thisnk是我不想要的东西的表,并且模型和制作我想要的东西的表。

3 个答案:

答案 0 :(得分: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

使用OR通常可以防止使用索引,因此使用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的一个子查询,仅用于make,一个仅用于model,另一个用于空。如果有3个表连接,则会扩展到8个子查询(即总有2个 n 子查询)。也许有人可以想出一个更好的方法,我无法想到这一点。

答案 1 :(得分: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)
      )

答案 2 :(得分: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