MySQL一条语句实现同时查询和修改
现在想仅执行一条mysql语句得到:查询到sid=2的用户,然后修改gid的值为123。
简单这样写:
1
|
UPDATE
`
user
`
SET
`gid`=
'123'
WHERE
id
IN
(
SELECT
id
FROM
`
user
`
WHERE
sid=2)
|
肯定会报错:
错误码: 1093
You can't specify target table 'user' for update in FROM clause
错误提示就是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)
解决办法:
1UPDATE
`
user
`
AS
A
INNER
JOIN
(
SELECT
id
FROM
`
user
`
WHERE
`sid`=2)
AS
B
ON
A.id=B.id
SET
A.gid=
'123'