PostgreSQL如何返回选择为数组

时间:2019-01-23 10:54:51

标签: sql postgresql

在PostgreSQL中:

说我有一张Users的桌子,我知道:

SELECT "EyeColor" FROM "Users" WHERE "Age" = 32

这将返回:

[
    {"EyeColor": "blue"},
    {"EyeColor": "green"},
    {"EyeColor": "blue"}
]

然后我想将blue, green, blue放入数组并使用它。这是我能得到的最接近的但不能正常工作:

SELECT * FROM "Eyes" WHERE "Color" IN
(SELECT array_agg("EyeColor") FROM "Users" WHERE "Age" = 32)

我希望anpve查询的功能与此相同:

SELECT * FROM "Eyes" WHERE "Color" IN ('blue', 'green')

1 个答案:

答案 0 :(得分:1)

您不需要将子查询结果聚合到一个数组中。您可以使用IN (subquery):

SELECT * 
FROM "Eyes" 
WHERE "Color" IN (
    SELECT "Eyes" 
    FROM "Users" 
    WHERE "Age" = 32)

ANY (subquery):

SELECT * 
FROM "Eyes" 
WHERE "Color" = ANY(
    SELECT "Eyes"
    FROM "Users" 
    WHERE "Age" = 32)