我该如何查询这个案例

时间:2013-01-26 19:56:53

标签: sql postgresql

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_idnull k.b_id

来获取数据

我该怎么做?

2 个答案:

答案 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

如果在jk中找不到匹配的行,NULL分别会为j.b_idk.b_id投放。

查询受到主要设计缺陷的影响,b中的多个匹配将乘以CROSS JOIN方式返回的行数。