Postresql使用另一个表中的子查询更新表

时间:2018-09-08 21:45:51

标签: postgresql

我正在使用postgressql,并尝试使用table2中credential_type的子查询来更新table1中的credential_flag列。我的子查询有效,但无法正确更新表1。这两个表都有一个用于联接的user_id字段。我的当前代码出现“连接时或连接附近的语法错误”

UPDATE table1
SET credential_flag =
  (SELECT DISTINCT ON (t2.user_id)
  CASE
  WHEN t2.credential_type LIKE 'AA/AS Degree%' THEN 1
  WHEN t2.credential_type LIKE 'Occupational Skills%' THEN 1
  ELSE 0 
  END 
  FROM t2)
JOIN table1 ON table1.user_id = t2.user_id;

1 个答案:

答案 0 :(得分:1)

您需要使用UPDATE FROM语法。 From the official documentation

UPDATE accounts SET contact_first_name = first_name,
                    contact_last_name = last_name
  FROM salesmen WHERE salesmen.id = accounts.sales_id;

在您的情况下,事实如此

UPDATE table1
SET credential_flag = (
  CASE
  WHEN t2.credential_type LIKE 'AA/AS Degree%' THEN 1
  WHEN t2.credential_type LIKE 'Occupational Skills%' THEN 1
  ELSE 0 
  END 
)
FROM t2
WHERE table1.user_id = t2.user_id;