UPDATE语句在WHERE子句中使用相同索引处的两个数组

时间:2017-05-20 14:38:21

标签: postgresql

我正在尝试使用列entities更新表contacts,该列是来自另一个表contacts的ID数组。联系人表格中包含first_namelast_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列。

1 个答案:

答案 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]
 );