SQL 更新 Select 语句子查询

问题描述 投票:0回答:1

我被 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

我需要使用 airports.ident 列更新 mytable.codeIcaoAirport,其中 codeIcaoAirport 字段为 NULL。为此,我尝试了此查询,该查询使用最后的记录 airports.ident 更新了所有代码IcaoAirports。我已经多次阅读该声明,但似乎无法找到为什么它会这样做

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

sql sqlite sql-update subquery
1个回答
0
投票

如果是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;
© www.soinside.com 2019 - 2024. All rights reserved.