子查询返回的多行

时间:2015-12-01 06:10:09

标签: sql postgresql coalesce

我有一个查询,我在使用coalesce来选择其中一个值。但是我得到一个错误,说明用作表达式的子查询返回了多行。我使用的是Postgres v9.3。 我的代码:

 select input1,
 input 2,
 (select (coalesce(tblstuff2.input4, '') || coalesce(tblstuff.input5, ''))
  from tblstuff
  join tblstuff2 on....
  where ...)
input 6,
from..
where...

我需要coalesce从表中添加两列(字符串)并显示为一个。例如:如果列输入4是手机号码而输入5是手机,则至少其中一个应该出现。

1 个答案:

答案 0 :(得分:0)

至少有三种解决方案:

不同

select distinct (coalesce(tblstuff2.input4, '') || coalesce(tblstuff.input5, ''))
  from tblstuff
  join tblstuff2 on....
  where ...

如果join返回相同的值。如果没有,则不起作用。

限制1

select (coalesce(tblstuff2.input4, '') || coalesce(tblstuff.input5, ''))
  from tblstuff
  join tblstuff2 on....
  where ...
  limit 1

如果join返回不同的值,但您丢失了其中一个。

string_agg

select string_agg(coalesce(tblstuff2.input4, '') || coalesce(tblstuff.input5, ''), ', ')
  from tblstuff
  join tblstuff2 on....
  where ...

如果join返回不同的值,并且您希望返回所有值。

相关问题