避免在 CASE 语句中进行 PostgreSQL 类型评估
Avoid PostgreSQL type evaluation in CASE statements
如果此列是 jsonb,我想 select 列键值。
如果它不是 jsonb,我只想 select 列。
代码如下:
SELECT
CASE WHEN (pg_typeof(mycolumn)::text LIKE 'jsonb')
THEN mycolumn->>'mykey'
ELSE mycolumn
END
FROM mytable;
它不起作用,因为仍然以某种方式对非 JSONB 类型的列求 mycolumn->>'mykey'
。
ERROR: operator does not exist: [...] ->> unknown
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
有没有办法让 PostgreSQL 类型检查接受这个语句,或者有任何其他方法可以做到这一点?
通常,您可以通过将查询结果转换为 text
:
来实现
SELECT
CASE WHEN (pg_typeof(mycolumn)::text LIKE 'jsonb')
THEN (mycolumn::text::jsonb)->>'mykey'
ELSE mycolumn::text
END
FROM mytable;
如果此列是 jsonb,我想 select 列键值。 如果它不是 jsonb,我只想 select 列。
代码如下:
SELECT
CASE WHEN (pg_typeof(mycolumn)::text LIKE 'jsonb')
THEN mycolumn->>'mykey'
ELSE mycolumn
END
FROM mytable;
它不起作用,因为仍然以某种方式对非 JSONB 类型的列求 mycolumn->>'mykey'
。
ERROR: operator does not exist: [...] ->> unknown
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
有没有办法让 PostgreSQL 类型检查接受这个语句,或者有任何其他方法可以做到这一点?
通常,您可以通过将查询结果转换为 text
:
SELECT
CASE WHEN (pg_typeof(mycolumn)::text LIKE 'jsonb')
THEN (mycolumn::text::jsonb)->>'mykey'
ELSE mycolumn::text
END
FROM mytable;