我有下表:
--------------------------------------------------------------------------------
| id | pack_id | user_id | start_date | end_date | runtime |
--------------------------------------------------------------------------------
| 1 | 52 | 9 | 2019-04-09 11:53:00 | 2019-04-09 11:54:00 | 60 |
| 2 | 52 | 9 | 2019-04-09 11:58:00 | NULL | NULL |
我想更新同一end_date
和runtime
的最后一个ID的pack_id
和user_id
。
end_date
必须采用当前日期时间。
这是我的查询:
UPDATE
myTable
SET
end_date = NOW(),
runtime = TIMESTAMPDIFF(SECOND, start_date, NOW())
WHERE
id = (
SELECT
max(id)
FROM
myTable
WHERE
user_id = '9'
AND
pack_id = '52'
)
然后出现以下错误:
第1行的错误1093(HY000):您无法指定目标表 “ myTable”用于FROM子句中的更新
答案 0 :(得分:1)
您无法在MySQL中执行此操作,因此请使用JOIN
:
UPDATE myTable t JOIN
(SELECT max(id) as max_id
FROM myTable
WHERE user_id = '9' AND pack_id = '52'
) tt
ON t.id = tt.max_id
SET t.end_date = NOW(),
t.runtime = TIMESTAMPDIFF(SECOND, t.start_date, NOW()) ;
答案 1 :(得分:0)
在子句中更深入地使用子查询
UPDATE
myTable
SET
end_date = NOW(),
runtime = TIMESTAMPDIFF(SECOND, start_date, NOW())
WHERE
id = (
select id from (
SELECT
max(id) as id
FROM
myTable
WHERE
user_id = '9'
AND
pack_id = '52'
) a
)
答案 2 :(得分:0)
您需要一个子查询来创建一个临时值集,并避免在同一级别使用同一表进行更新和选择。 您可以使用嵌套选择进行操作,例如:
UPDATE myTable
SET end_date = NOW(),
runtime = TIMESTAMPDIFF(SECOND, start_date, NOW())
WHERE id = (
select max_id from (
SELECT
max(id) max_id
FROM myTable
WHERE user_id = '9'
AND pack_id = '52'
) t )
或子查询上的内部联接
UPDATE myTable m
INNER JOIN (
SELECT
max(id) max_id
FROM myTable
WHERE user_id = '9'
AND pack_id = '52'
) t ON t.max_id = m.id
SET end_date = NOW(),
runtime = TIMESTAMPDIFF(SECOND, start_date, NOW())