我有一个问题:
SELECT bar, (SELECT name FROM names WHERE value = bar) as name
FROM foobar WHERE foo = 1 and bar = ANY (1,2,3)
我的问题是,当表bar = 3
中没有包含foobar
(或请求的任何其他值)的行时,不会为该值的bar返回任何行。
我希望我的查询返回[bar, NULL]
行,但无法想办法解决这个问题。
这甚至可能吗?
答案 0 :(得分:14)
也许这种方法就像你所追求的那样:
测试平台:
create view names as
select 1 as value, 'Adam' as name union all select 2, 'Beth';
create view foobar as
select 1 as foo, 1 as bar union all select 1, 2;
原始方法:
select bar, (select name from names where value = bar) as name
from foobar
where foo = 1 and bar = any (array[1, 2, 3]);
bar | name
-----+------
1 | Adam
2 | Beth
(2 rows)
替代方法:
with w as (select unnest(array[1, 2, 3]) as bar)
select bar, (select name from names where value = bar) as name
from w left outer join foobar using(bar);
bar | name
-----+------
1 | Adam
2 | Beth
3 |
(3 rows)
如果您使用的是8.3或之前,则没有内置的unnest
功能,但您可以自己动手(非常有效)替换:
create or replace function unnest(anyarray) returns setof anyelement as $$
select $1[i] from generate_series(array_lower($1,1), array_upper($1,1)) i;
$$ language 'sql' immutable;
答案 1 :(得分:1)
SELECT bar, name
FROM foobar
INNER JOIN names ON foobar.bar = names.value
WHERE foo = 1 and bar = ANY (1,2,3)
请尝试该查询。
答案 2 :(得分:1)
SELECT vals.bar, name
FROM (
SELECT *
FROM unnest([1, 2, 3]) AS bar
) vals
LEFT JOIN
foobar
ON foobar.foo = 1
AND foobar.bar = vals.bar
LEFT JOIN
names
ON names.value = vals.bar