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