提问人:user22743392 提问时间:10/18/2023 最后编辑:user22743392 更新时间:10/18/2023 访问量:37
SQL Update Select 语句子查询
SQL Update Select Statement Subquery
问:
我被困在 SQL 更新语句上,并希望得到有关我出错之处的指导。
下面的查询将产生以下结果。
SELECT a.ident, a.iata_code, m.nameAirport, m.codeIataAirport, m.codeIcaoAirport FROM airports a
INNER JOIN mytable m ON m.codeIataAirport = a.iata_code
where m.codeIcaoAirport IS NULL
结果:
ident. iata_code. nameAirport. codeIataAirport. codeIcaoAirport
OIAG. AKW. Aghajari. AKW. NULL
FMNE. AMB. Ambilobe. AMB. NULL
FTTU. AMO. Mao. AMO. NULL
我需要使用 codeIcaoAirport 字段为 NULL 的 airports.ident 列更新 mytable.codeIcaoAirport。在这样做时,我尝试了这个查询,该查询使用最后记录 airports.ident 更新了所有 codeIcaoAirports。我已经多次通读了该声明,但似乎找不到它为什么要这样做
WITH subquery AS (
SELECT a.ident, m.nameAirport, m .codeIcaoAirport FROM airports a
INNER JOIN mytable m ON m.codeIataAirport = a.iata_code
where m.codeIcaoAirport IS NULL
)
UPDATE mytable
SET codeIcaoAirport = subquery.ident
FROM subquery;
如何重构此查询以使用 airports.ident 值更新 mytable.codeIcaoAiport。表之间的连接位于内部联接或 m.codeIataAirport = a.iata_code
答:
1赞
Senthil P Nathan
10/18/2023
#1
如果是SQLite,则可以使用它。
-- before the update
SELECT * FROM mytable;
-- Update "mytable" based on the "airports" table
UPDATE mytable
SET codeIcaoAirport = (SELECT ident FROM airports WHERE airports.iata_code = mytable.codeIataAirport)
WHERE codeIcaoAirport IS NULL;
-- after the update
SELECT * FROM mytable;
评论
UPDATE m SET m.codeIcaoAirport = a.ident FROM airports a INNER JOIN mytable m ON m.codeIataAirport = a.iata_code WHERE m.codeIcaoAirport IS NULL;