[英]MYSQL: SELECT and UPDATE in the same statement won't work - 1064 error
I have an UPDATE and SELECT statement working in SQL however I am unable to replicate the same outcome in MYSQL.我有一个在 SQL 中工作的 UPDATE 和 SELECT 语句,但是我无法在 MYSQL 中复制相同的结果。
I have a table (TBL1) with, say 4 columns:-我有一张桌子(TBL1),有 4 列:-
col1: registration (VARCHAR)
col2: date
col3: oldest date flag (values Y or blank)
col4: index (priamry key - auto-increment).
An ongoing process continues to add registrations and dates to the table.一个正在进行的过程继续向表中添加注册和日期。 After a batch of additions any col3 'Y' flags will be removed and then an update process will set the col3 value = 'Y' for each the row where the registration has the oldest date.在一批添加之后,任何 col3 'Y' 标志将被删除,然后更新过程将为注册日期最早的每一行设置 col3 值 = 'Y'。
Here is the SQL code, this works as expected after an earlier process removes any previous col3 'Y' values;-这是 SQL 代码,在较早的过程删除任何先前的 col3 'Y' 值后,它按预期工作;-
UPDATE T1
SET T1.Col3 = 'Y'
SELECT FROM TBL1 AS T1
INNER JOIN ( SELECT Col1 AS REG, MIN(Col2) AS MINDATE
FROM TBL1
GROUP BY Col1) AS T2
ON T1.Col1 = T2.REG and T1.Col2 = T2.MINDATE
The result correctly recognises for each unique registration the oldest date and sets 'Y' in col3.结果正确识别每个唯一注册的最旧日期并在 col3 中设置“Y”。
I need to replicate this process in MYSQL but after much effort I can't find a way to do this?我需要在 MYSQL 中复制这个过程,但经过很多努力我找不到办法做到这一点?
If you are just looking for the same logic, but with MySQL's update join syntax, then try this:如果您只是在寻找相同的逻辑,但使用 MySQL 的更新连接语法,请尝试以下操作:
UPDATE TBL1 T1
INNER JOIN
(
SELECT Col1 AS REG, MIN(Col2) AS MINDATE
FROM TBL1
GROUP BY Col1
) AS T2
ON T1.Col1 = T2.REG and T1.Col2 = T2.MINDATE
SET T1.Col3 = 'Y';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.