ToB企服应用市场:ToB评测及商务社交产业平台

标题: MySQL出现You can‘t specify target table for update in FROM clause错误 [打印本页]

作者: 郭卫东    时间: 2024-10-22 00:19
标题: MySQL出现You can‘t specify target table for update in FROM clause错误
分析缘故原由
在MySQL中,可能会遇到You can't specify target table '表名' for update in FROM clause这样的错误
它的意思是说,不能在同一语句中,先select出同一表中的某些值,再update这个表,即不能依据某字段值做判定再来更新某字段的值。
这个问题在MySQL官网中有提到解决方案:MySQL-UPDATE- 拉到文档下面
比方下面这张t_message表
+----+-----+-----------+---------------------+
| id | uid | content   | addtime             |
+----+-----+-----------+---------------------+
|  1 |   1 | content1  | 2022-04-26 00:00:01 |
|  2 |   2 | content2  | 2022-04-26 00:00:02 |
|  3 |   3 | content3  | 2022-04-26 00:00:03 |
|  4 |   1 | content4  | 2022-04-26 00:00:04 |
|  5 |   3 | content5  | 2022-04-26 00:00:05 |
|  6 |   2 | content6  | 2022-04-26 00:00:06 |
|  7 |   2 | content7  | 2022-04-26 00:00:07 |
|  8 |   4 | content8  | 2022-04-26 00:00:08 |
|  9 |   4 | content9  | 2022-04-26 00:00:09 |
| 10 |   1 | content10 | 2022-04-26 00:00:10 |
+----+-----+-----------+---------------------+

我想将每个用户第一条消息的内容更新为Hello World
  1. UPDATE t_message
  2. SET content = 'Hello World'
  3. WHERE id IN (
  4.                          SELECT min(id) FROM t_message GROUP BY uid
  5.                         );
  6. -- 会出现如下错误
  7. -- ERROR 1093: You can't specify target table 't_message' for update in FROM clause
  8. -- 解决方法:select 的结果再通过一个中间表 select 多一次,就可以避免这个错误
  9. UPDATE message
  10. SET content = 'Hello World'
  11. WHERE id IN (
  12.                         SELECT min_id FROM (
  13.                                   SELECT min(id) AS min_id FROM t_message GROUP BY uid
  14.                                                                 ) AS a
  15.                         );
  16. -- 更新的其他方式
  17. update fa_info fb, (
  18.   select
  19.     fb.member_id as oldMemberId,
  20.     mc.id as newMemberCardId
  21.   from
  22.     fa_info fb
  23.     inner join ott_member m on fb.member_id = m.id and m.is_deleted = 0
  24.     left join ott_card c on m.idcard_no = c.idcard_no and m.type = c.type and c.is_deleted = 0
  25.     inner join ott_member_card mc on mc.member_id = m.id and (mc.card_id = c.id or mc.card_id is null) and mc.is_deleted = 0
  26. ) mm
  27. set fb.member_id = mm.newMemberCardId
  28. where mm.oldMemberId = fb.member_id;
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4