PostgreSQL UNION between Integer and JSONB get error : UNION types integer and jsonb cannot be matched
PostgreSQL UNION between Integer and JSONB get error : UNION types integer and jsonb cannot be matched
我想使用 UNION ALL 运算符将 2 个 table 合并为一个。
第一个 table 有几个字段。第二个 table 将几个字段分组到 JSONB 字段中。
为了简化问题,我通过使用这个简单的SQL请求(不依赖于table)重现了错误:
SELECT 10 as price
UNION ALL
SELECT '{"price":2}'::jsonb->'price' as price;
此请求return出现以下错误:
ERROR: UNION types integer and jsonb cannot be matched
LINE 3: SELECT '{"price":2}'::jsonb->'price' as price;
如何使用 UNION ALL 运算符将整数与 JSONB 整数 属性 合并?
我想获得以下输出:
price
-------
10
2
(2 rows)
JSON 看起来很简单,但在处理类型时会变得有点复杂。您想要提取 元素 作为值;然后,您可以转换为整数。因此:
SELECT 10 as price
UNION ALL
SELECT ('{"price":2}'::jsonb->>'price')::int as price
->
运算符 returns 一个 JSONB 值,而不是整数。您需要使用 ->>
运算符 which returns a text
然后将其转换为整数:
SELECT 10 as price
UNION ALL
SELECT ('{"price":2}'::jsonb->>'price')::int as price;
我想使用 UNION ALL 运算符将 2 个 table 合并为一个。 第一个 table 有几个字段。第二个 table 将几个字段分组到 JSONB 字段中。
为了简化问题,我通过使用这个简单的SQL请求(不依赖于table)重现了错误:
SELECT 10 as price
UNION ALL
SELECT '{"price":2}'::jsonb->'price' as price;
此请求return出现以下错误:
ERROR: UNION types integer and jsonb cannot be matched
LINE 3: SELECT '{"price":2}'::jsonb->'price' as price;
如何使用 UNION ALL 运算符将整数与 JSONB 整数 属性 合并?
我想获得以下输出:
price
-------
10
2
(2 rows)
JSON 看起来很简单,但在处理类型时会变得有点复杂。您想要提取 元素 作为值;然后,您可以转换为整数。因此:
SELECT 10 as price
UNION ALL
SELECT ('{"price":2}'::jsonb->>'price')::int as price
->
运算符 returns 一个 JSONB 值,而不是整数。您需要使用 ->>
运算符 which returns a text
然后将其转换为整数:
SELECT 10 as price
UNION ALL
SELECT ('{"price":2}'::jsonb->>'price')::int as price;