如何从链接表更新表? [英] How to update table from linking table?
问题描述
我正在使用PostgreSQL数据库并在黑暗中查询.我有三(3)个表:zip_code
,zip_code_type
和temp_zip_type
.它们包含以下列:
I am using a PostgreSQL database and querying in the dark here. I have three (3) tables: zip_code
, zip_code_type
, and temp_zip_type
. They have the following columns:
zip_code
zip_5_digit text
type_id integer
zip_code_type
id integer
value text
temp_zip_type
temp_zip text
temp_type text
我正在尝试更新zip_code
和SET zip_code.type_id = zip_code_type.id
,以使zip_code.zip_5_digit
与temp_zip_type.temp_zip
匹配,而temp_zip_type.temp_type
与zip_code_type.value
匹配.
I am trying to UPDATE zip_code
and SET zip_code.type_id = zip_code_type.id
so that zip_code.zip_5_digit
matches with temp_zip_type.temp_zip
, and temp_zip_type.temp_type
matches zip_code_type.value
.
这是我的尝试:
UPDATE
zip_code
SET
type_id =
(
SELECT
id
FROM
zip_code_type
JOIN
temp_zip_type
ON
temp_type = value
WHERE
temp_zip = zip_5_digit
);
我要查找的结果是type_id
通过查找表中的值来匹配zip_code_type.id
中的值.
The result I am looking for is the type_id
match the value in zip_code_type.id
by looking up the values across the tables.
我更改了temp_zip_type
并添加了一个名为temp_type_id
的整数列.通过执行以下查询,我得到了想要的结果:
I altered temp_zip_type
and added an integer column called temp_type_id
. I got the results I wanted by executing the following queries:
UPDATE
temp_zip_type
SET
temp_type_id =
(
SELECT
id
FROM
zip_code_type
WHERE
temp_type = value
);
UPDATE
zip_code
SET
type_id =
(
SELECT
temp_type_id
FROM
temp_zip_type
WHERE
zip_5_digit = temp_zip
);
供以后参考,是否有更有效的查询?这些查询需要147秒才能完成.
For future reference, is there a more efficient query? These queries took 147 seconds to complete.
推荐答案
Use the FROM
clause of UPDATE
to join temp_zip_type
and zip_code_type
and do it all in one simple statement:
UPDATE zip_code z
SET type_id = t.id
FROM temp_zip_type tmp
JOIN zip_code_type t ON t.value = tmp.temp_type
WHERE z.zip_5_digit = tmp.temp_zip
AND z.type_id IS DISTINCT FROM t.id; -- avoid empty updates
我添加了最后一行以避免空更新.它可能有用也可能没有用.详细信息:
I added the last line to avoid empty updates. It may or may not be useful. Details:
这篇关于如何从链接表更新表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!