MySQL一条语句实现同时查询和修改
现在想仅执行一条mysql语句得到:查询到sid=2的用户,然后修改gid的值为123简单可以这样写:
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这个表(在同一语句中)
解决办法:
UPDATE user AS A INNER JOIN (SELECT id FROM user WHERE sid=2) AS B ON A.id=B.id SET A.gid=‘123’
本次案例中有个需求就是将一张表中的名字改成父表名字加字表名字加编号
SQL如下:
UPDATE `MP_Channel` AS A INNER JOIN (SELECT Temp.* FROM (SELECT Channel.`Index`, CONCAT(MonitorPoint.`Name`,Direction.`Name`) AS `name` FROM `MP_Channel` AS Channel LEFT JOIN `MP_Direction` AS Direction ON Direction.`Index`=Channel.`DirectionIndex` LEFT JOIN `MP_MonitorPoint` AS MonitorPoint ON MonitorPoint.`Index` = Channel.`MPIndex`) AS Temp) AS B SET A.`Name` = B.name WHERE A.`Index` = B.Index
UPDATE `MP_Channel` SET `Name` =CONCAT (`Name`,`NO`,'车道')
这里我分了两步来操作,减少代码的复杂程度
- 上一篇:没有了
- 下一篇:没有了
相关文章
MySQL一条语句实现同时查询和修改
现在想仅执行一条mysql语句得到:查询到sid=2的用户,然后修改gid的值为123 简单可以这样写: UPDATEuserSETgid=123 WHERE id IN (SELECT id FROMuser WHERE sid=2) 肯定会报错: 错误码: 1093 You cant specify ...
2021-07-31