MySQL 查询适用于 SELECT 但不适用于 UPDATE 语句
Posted
技术标签:
【中文标题】MySQL 查询适用于 SELECT 但不适用于 UPDATE 语句【英文标题】:MySQL query works for SELECT but not with UPDATE statement 【发布时间】:2021-02-23 14:01:50 【问题描述】:我遇到了一个问题,我的第一个查询 (SELECT) 工作正常,但是当我尝试执行我的第二个查询 (UPDATE) 时出现错误。有人可以帮我知道我在这里做错了什么吗?
QUERY 1:
WITH res AS (
SELECT str.request_id as requestID, str.type as incorrectType, TxType.utType as correctType
FROM x str
JOIN (
SELECT tr.request_id, ut.type AS utType
FROM x tr
JOIN y tc ON tr.request_id = tc.request_id
JOIN z ut ON tc.transaction_id = ut.id
) AS TxType ON str.request_id = TxType.request_id
WHERE str.type != TxType.utType
AND str.application = 'sample' LIMIT 1
)
SELECT * FROM x tr_req
JOIN res AS re ON re.requestID = tr_req.request_id
WHERE tr_req.type != re.correctType;
RESULT : SUCCESS
QUERY : 2
WITH res AS (
SELECT str.request_id as requestID, str.type as incorrectType, TxType.utType as correctType
FROM x str
JOIN (
SELECT tr.request_id, ut.type AS utType
FROM x tr
JOIN y tc ON tr.request_id = tc.request_id
JOIN z ut ON tc.transaction_id = ut.id
) AS TxType ON str.request_id = TxType.request_id
WHERE str.type != TxType.utType
AND str.application = 'sample' LIMIT 1
)
UPDATE x tr_req
JOIN res AS re ON re.requestID = tr_req.request_id
SET tr_req.type = re.correctType
WHERE tr_req.type != re.correctType;
RESULT : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE x tr_req
【问题讨论】:
谢谢@P.Salmon,我需要一个限制。有超过 90 万条记录需要更新。我需要以几千个批次执行此操作,以确保它不会超时。 关于分块的更多信息:mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks(这些原则适用于 UPDATE。) 【参考方案1】:您正在使用 MariaDB。 Here is the documentation of WITH.
正如您在语法中看到的,它仅适用于 SELECT:
WITH [RECURSIVE] table_reference [(columns_list)] AS (
SELECT ...
)
[CYCLE cycle_column_list RESTRICT]
SELECT ...
没有更新选项。
【讨论】:
以上是关于MySQL 查询适用于 SELECT 但不适用于 UPDATE 语句的主要内容,如果未能解决你的问题,请参考以下文章
MySQL 查询适用于 Workbench,但不适用于 C# 代码
在单个 MySQL 查询中使用多个临时表(适用于 phpMyAdmin,但不适用于 PHP)
sql 脚本适用于 MySQL,但不适用于 google bigquery
查询适用于 phpMyAdmin,但不适用于 Java [重复]