SQL Update Select 语句子查询

SQL Update Select Statement Subquery

提问人:user22743392 提问时间:10/18/2023 最后编辑:user22743392 更新时间:10/18/2023 访问量:37

问:

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

sql sqlite sql-update 子查询

评论

0赞 Senthil P Nathan 10/18/2023
查看此代码,此代码适用于 SQL Server。删除了 CTE 并进行了直接更新。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;
0赞 user22743392 10/18/2023
返回语法错误 Execution finished with errors。结果:接近“.”:语法错误 在第 1 行:UPDATE m SET m。我正在使用DB Browser for SQLite
0赞 user22743392 10/18/2023
修改了更新语句,将 UPDATE mytable SET codeIcaoAirport = a.ident FROM airports a INNER JOIN mytable m ON m.codeIcaoAirport = a.iata_code WHERE m.codeIcaoAirport IS NULL;这再次将所有 codeIcaoAirport 记录更新为以下查询中的最后一条记录。select a.ident FROM airports a INNER JOIN mytable m ON m.codeIataAirport = a.iata_code WHERE m.codeIcaoAirport IS NULL;
0赞 philipxy 10/19/2023
请通过编辑而不是评论进行澄清。请删除并标记过时的评论。调试问题需要一个最小的可重现示例Stack Overflow 用户需要付出多少研究努力? 如何咨询帮助中心
0赞 philipxy 10/19/2023
请提出 1 个经过研究的非重复问题。请询问 1 个错误的查询/函数,并提供强制性的最小可重现示例,包括为什么您认为它应该返回其他内容,或者不确定在第一个子表达式中您没有得到您期望或卡住的地方,通过参考权威文档进行证明,或者询问您的总体目标,给出您可以用理由和最小可现示例来做的工作部分--那么被误解的代码就不属于了。但是,请首先询问意外行为,因为误解会妨碍您的目标。基本问题是常见问题解答。

答:

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;