我有下面的CREATE View语句,其中我正在连接几个字段。它抓取第一个字段的前100个字符,然后附加一个整数字段
CREATE OR REPLACE VIEW $"schema_1"."tbl_225_customid" AS
SELECT tbl_225.id,
("substring"((field_2)::text, 0, 100)::text) || ' (' || "field_1" || ')' as fullname
FROM schema_1.tbl_225;
当field_2中有数据时,这个方法可以正常工作,但是当field_2为空时,视图会显示NULL,而不是只显示表达式的整数部分。
我试着用这样的coalesce语句来包装,但它会抛出一个错误。
CREATE OR REPLACE VIEW $"schema_1"."tbl_225_customid" AS
SELECT tbl_225.id,
COALESCE(("substring"((field_2)::text, 0, 100)::text),'') || ' (' || "field_1" || ')' as fullname
FROM schema_1.tbl_225;
我如何编写concat字符串,使其在field_2为空的情况下,使用''来表示,并且仍然产生值?
我建议简单地使用 字符串 concat_ws()
为此:它忽略了 null
价值的设计,所以你只要不用担心他们。
select
tbl_225.id,
concat_ws('', substring(field_2::text, 0, 100), ' (' || field_1 || ')') as fullname
from schema_1.tbl_225;
使用 coalesce()
:
SELECT tbl_225.id,
COALESCE(substring(field_2::text, 0, 100) , '') || coalesce(' (' || "field_1" || ')', '') as fullname
FROM schema_1.tbl_225;