DB:PostgreSQL
假设我有
table A(integer a_id, timestamp x, timestamp y)
table B(int b_id, timestamp n, timestamp m)
m
可以是null
我想用这种结构获取数据
SELECT a_id, j.b_id, k.b_id
FROM A, B AS j, B AS k
WHERE (x BETWEEN j.n AND j.m) AND (y BETWEEN k.n AND k.m.)
找不到(x BETWEEN j.n AND j.m) AND (y BETWEEN k.n AND k.m.)
的匹配时
我仍然希望查询使用null j.b_id
或null k.b_id
我该怎么做?
答案 0 :(得分:1)
在NULL中使用外连接和因子:
SELECT a_id, j.b_id, k.b_id
FROM A
LEFT JOIN B AS j ON x >= j.n AND (x <= j.m OR j.m IS NULL)
LEFT JOIN B AS k ON y >= k.n AND (y <= k.m OR k.m IS NULL)
答案 1 :(得分:1)
我对这个神秘问题的解释......
SELECT a_id, j.b_id, k.b_id
FROM a
LEFT JOIN b j ON a.x BETWEEN j.n AND j.m
LEFT JOIN b k ON a.y BETWEEN k.n AND k.m
如果在j
或k
中找不到匹配的行,NULL
分别会为j.b_id
或k.b_id
投放。
查询受到主要设计缺陷的影响,b
中的多个匹配将乘以CROSS JOIN
方式返回的行数。