我正在尝试使用列entities
更新表contacts
,该列是来自另一个表contacts
的ID数组。联系人表格中包含first_name
和last_name
列,我有一系列名字firstNames
和姓氏,lastNames
可以传入。
如何更新contacts
表格中的entities
列,其中一个查询可以正确获取名为firstNames[0]
和姓氏为lastNames[0]
的所有联系人,以及所有名字为firstNames[1]
和姓氏为lastNames[1]
的联系人,以及[...]所有名字为firstNames[n]
且姓氏为lastNames[n]
的联系人?
我最初的想法是UPDATE entities SET contacts = (SELECT id FROM contacts WHERE first_name = ANY(firstNames) AND last_name = ANY(lastNames)
。
当contacts
表格如下所示时,问题就出现了:
first_name | last_name
----------------------
Bob | Jones
Bob | Miller
David | Miller
如果我想将contacts
列设置为Bob Jones和David Miller的ID,而不是Bob Miller,我将['Bob', 'David']
传递给firstNames
和{{1}对于上述查询中的['Jones', 'Miller']
,Bob Miller也会添加到lastNames
列。
答案 0 :(得分:0)
可能你想找到这样的东西:
WITH x AS (
SELECT 'Bob'::text AS firstName, 'Jones'::text AS lastName
UNION SELECT 'David', 'Miller'
UNION SELECT 'Bob', 'Miller'
)
SELECT *
FROM x
WHERE (firstName, lastName) = ANY (ARRAY [
('Bob'::text, 'Jones'::text),
('David'::text, 'Miller'::text)
]);
另一种方式:
WITH x AS (
SELECT 'Bob'::text AS firstName, 'Jones'::text AS lastName
UNION SELECT 'David', 'Miller'
UNION SELECT 'Bob', 'Miller'
)
SELECT *
FROM x
WHERE EXISTS (
SELECT 1
FROM (SELECT ARRAY [
['Bob', 'Jones'],
['David', 'Miller']]::text[][] AS n
) AS n
JOIN LATERAL generate_series(1, array_upper(n, 1)) AS i ON true
WHERE firstName = n[i][1]
AND lastName = n[i][2]
);