SQL:检查数组中是否至少有一个元素在子查询中
SQL: Check if at least one element of an array is in subquery
我有一个 table 这样的:
id | name | artists
-------------------
1 | XYZ | {Some Dude, Whatever}
2 | ABC | {Blah Blah Blah, Whatever}
3 | EFG | {Running, Out, Of, Made, Up, Names}
我有一个子查询,其中 returns 一个名为 name
的列带有一堆艺术家的名字。我需要一种方法来检查 artists
的至少一个元素(对于每一行)是否包含在该子查询的结果中。也就是说,如果子查询returns this:
name
----
Some Dude
Whatever
Blah Blah Blah
然后,在我的示例中,我只想 select id 为 1 和 2 的行,因为子查询返回了 id 3 中 none 的艺术家。
我知道我可以做到 single_element = ANY(subquery)
但这只测试单个元素。我尝试过:
SELECT * FROM table WHERE ANY(artists) = ANY(subquery)
但是 "ERROR: syntax error at or near 'any'".
立即失败
提前致谢!
您可以使用 &&
运算符来测试集合元素重叠。它记录在 postgresql documentation section on array functions
WITH artists (name) AS (
VALUES
('Blah Blah Blah'::text),
('Whatever'),
('Some Dude')
),
my_table (id, name, artists) AS (
VALUES
(1,'XYZ',ARRAY['Some Dude'::TEXT, 'Whatever'::TEXT]),
(2,'ABC',ARRAY['Blah Blah Blah', 'Whatever']),
(3,'EFG',ARRAY['Running', 'Out', 'Of', 'Made', 'Up', 'Names'])
)
SELECT *
FROM my_table
WHERE artists && (SELECT ARRAY_AGG(name) FROM artists)
此外,从我上面的示例中,您可以看到如何将子查询转换为数组以便能够使用 overlaps
运算符
我有一个 table 这样的:
id | name | artists
-------------------
1 | XYZ | {Some Dude, Whatever}
2 | ABC | {Blah Blah Blah, Whatever}
3 | EFG | {Running, Out, Of, Made, Up, Names}
我有一个子查询,其中 returns 一个名为 name
的列带有一堆艺术家的名字。我需要一种方法来检查 artists
的至少一个元素(对于每一行)是否包含在该子查询的结果中。也就是说,如果子查询returns this:
name
----
Some Dude
Whatever
Blah Blah Blah
然后,在我的示例中,我只想 select id 为 1 和 2 的行,因为子查询返回了 id 3 中 none 的艺术家。
我知道我可以做到 single_element = ANY(subquery)
但这只测试单个元素。我尝试过:
SELECT * FROM table WHERE ANY(artists) = ANY(subquery)
但是 "ERROR: syntax error at or near 'any'".
立即失败提前致谢!
您可以使用 &&
运算符来测试集合元素重叠。它记录在 postgresql documentation section on array functions
WITH artists (name) AS (
VALUES
('Blah Blah Blah'::text),
('Whatever'),
('Some Dude')
),
my_table (id, name, artists) AS (
VALUES
(1,'XYZ',ARRAY['Some Dude'::TEXT, 'Whatever'::TEXT]),
(2,'ABC',ARRAY['Blah Blah Blah', 'Whatever']),
(3,'EFG',ARRAY['Running', 'Out', 'Of', 'Made', 'Up', 'Names'])
)
SELECT *
FROM my_table
WHERE artists && (SELECT ARRAY_AGG(name) FROM artists)
此外,从我上面的示例中,您可以看到如何将子查询转换为数组以便能够使用 overlaps
运算符