假设我在Postgres中有以下表模式:

CREATE TABLE users (id text, email text, phone_number text);

无论出于什么原因,我都想将电子邮件和电话号码选择为JSON:
SELECT to_json(users.email, users.phone_number) AS user FROM users WHERE id=usr_123;

我发现一个错误如下:
function to_json(text, text) does not exist

No function matches the given name and argument types. You might need to add explicit type casts.

但这很管用:
SELECT to_json(users.*) AS user FROM users WHERE id=usr_123;

如何使用Postgres中的to_json调用仅选择几列(不是所有列)?

最佳答案

使用子查询,例如:

select to_json(sub)
from (
    select email, phone_number
    from users
    where id = 'usr_123'
    ) sub;

with查询:
with cte as (
    select email, phone_number
    from users
    where id = 'usr_123')
select to_json(cte)
from cte;

关于json - 使用Postgres在多个列上调用to_json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32674077/

10-11 19:32
查看更多