mysql - 从另一个表更新多次

标签 mysql sql

我使用这个查询它只获取最后一个媒体并将其从表 1 中删除

UPDATE table1
        join
    table2 as b ON table1.tree_points_guid = b.tree_points_guid
        left outer join
    table3 as m ON table1.media_guid like concat('%', m.media_guid, '%') 
set 
    table1.media_guid = REPLACE(table1.media_guid,
        concat(m.media_guid, '_', media_type_guid),
        '')
where
    m.media_setting_guid = '3be0eead659d'
        and m.user_guid <> b.user_guid
        and table1.media_guid like concat('%', m.media_guid, '%')
;

我有

tree_point_media  media_guid 
1                     1|2|3

更新后我要

tree_point_media  media_guid 
1                     null

但我的查询只做

tree_point_media  media_guid 
1                    1|2|

在同一个查询上单击三次后,我可以获得我想要的结果 但我想只执行一次

最佳答案

MySQL 文档非常清楚当join 中有多个匹配项时会发生什么:

For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. Each matching row is updated once, even if it matches the conditions multiple times. For multiple-table syntax, ORDER BY and LIMIT cannot be used.

也就是说,任意匹配行之一用于更新。

在您的情况下,真正的解决方案——正如 Barmar 在评论中所建议的那样——是有一个适当的联结表,每个 tree_point_mediamedia_guid 一行。在那种情况下,“更新”会很简单,一个简单的 delete 语句。将事物列表存储在字符串中不是一个好主意。存储数字 id 列表是双重糟糕的,因为您将整数存储为字符串。 SQL 具有用于存储列表的出色数据结构;它被称为表。

如果由于某种原因您无法创建联结表,则您的选择相当有限。在这种情况下,最简单的解决方案是编写一个存储过程,在循环中重复执行更新,直到没有记录匹配为止。

关于mysql - 从另一个表更新多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26323182/

相关文章:

Mysql:对同一个表使用两个外键

sql - 是否有任何纯 sql 方法可以通过以下方式从日志表中删除数据

php - 日期时间比较 PHP/Mysql?

php - 自然连接不返回行

python - 关闭终端后未退出 "Connection refused"错误。 Django 1.8

MySQL从字符串中选择字段

sql - 找出谁在从存储过程中执行该存储过程

mysql - 多字段值的 SQL 查询

php - PHP 脚本中的一般 "Killed"错误

mysql - RMySQL : SQL Syntax error unidentifiable