0

数据库:PostgreSQL

假设我有

table A(integer a_id, timestamp x, timestamp y) 
table B(int b_id, timestamp n, timestamp m)

mnull

我想用这个结构获取数据

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我仍然希望查询使用or获取数据null k.b_id

我怎么做?

4

2 回答 2

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) 
于 2013-01-26T20:02:57.450 回答
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如果在or中没有找到匹配的行kNULL则分别为j.b_idor传递k.b_id

该查询受到主要设计缺陷的影响,即多个匹配项将以某种方式b返回的行数成倍增加。CROSS JOIN

于 2013-01-26T20:13:32.513 回答