mysql - 更新以复合键连接的表

标签 mysql join composite-key

我正在尝试更新与较小索引表中的行相交的数据表中的行。这两个表在数据表的复合 PK 上连接,使用相同条件的解释选择表明索引被正确使用,并且提取了正确的唯一行 - 但我仍然遇到更新问题。

当临时表中只有 1 行时,连接表的更新工作正常,但当我有更多行时,我得到 MySql Error 1175 ,并且我指定的 WHERE 条件均未被识别。

我知道我可以使用 SET SQL_SAFE_UPDATES=0 关闭安全模式,但是谁能告诉我我在这里不明白的是什么?为什么我的 WHERE 条件不被接受,为什么当我进行 NATURAL JOIN 时它甚至需要一个 where - 为什么这只适用于右侧表 (MyTempTable) 中的一行?

代码

下面大大简化了,但结构相同,创建表和更新代表我的问题。

-- The Data Table.
Create Table MyDataTable
(
    KeyPartOne int not null,
    KeyPartTwo varchar(64) not null,
    KeyPartThree int not null,
    RelevantData varchar(200) null,
    Primary key (KeyPartOne, KeyPartTwo, KeyPartThree)
) Engine=InnoDB;

-- The 'Temp' table.
Create Table MyTempTable
(
    KeyPartOne int not null,
    KeyPartTwo varchar(64) not null,
    KeyPartThree int not null,
    Primary key (KeyPartOne, KeyPartTwo, KeyPartThree)
)Engine=Memory;

-- The Update Query (works fine with only 1 row in Temp table)
update MyDataTable natural join MyTempTable 
set RelevantData = 'Something Meaningful';

-- Specifying 'where' - roduces same effect as the other update query
update MyDataTable mdt join MyTempTable mtt
on mdt.KeyPartOne = mtt.KeyPartOne
and mdt.KeyPartTwo = mtt.KeyPartTwo
and mdt.KeyPartThree = mtt.KeyPartThree
set RelevantData = 'Something Meaningful'
where mdt.KeyPartOne = mtt.KeyPartOne
and mdt.KeyPartTwo = mtt.KeyPartTwo
and mdt.KeyPartThree = mtt.KeyPartThree;

附言当临时表只包含一行时,上面的两个更新语句都按预期工作,但是当有多于一行时给我错误。我很好奇为什么!

最佳答案

在您的第一个 UPDATE 查询中,您使用了 NATURAL JOIN,这与 NATURAL LEFT JOIN 相同。

在您的第二个UPDATE 查询中,您使用JOIN,这与INNER JOIN 相同。

LEFT JOININNER JOIN 不同,NATURAL JOINJOIN 不同

不确定您要做什么,但是如果您尝试更新 MyDataTable 中的所有行,而 MyTempTable 中存在相应的条目,则此查询应该可以解决问题:

UPDATE
    myDataTable mdt
    INNER JOIN MyTempTable mtt ON
        mdt.KeyPartOne = mtt.KeyPartOne
        AND mdt.KeyPartTwo = mtt.KeyPartTwo
        AND mdt.KeyPartThree = mtt.KeyPartThree
SET
    mdt.RelevantData = 'Something Meaningful'

如果这不是您想要做的,请澄清,我会更新我的答案。

关于mysql - 更新以复合键连接的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9798016/

相关文章:

mysql - 我是否需要使用插入或内部联接?

database - 使用 CouchDB 的复合键,查找多条记录

jpa - 插入具有复合主键的对象

mysql - 将列转换为行并获取最新值

mysql - 在带有法语口音的 MySQL 中编码

mysql - 排序依据和分组依据

sql - NULL 在连接中不匹配

mysql - 如何格式化并打印sql查询结果

mysql - 查询 WHERE NOT IN (SELECT) INNER JOIN

MySQL没有使用复合索引的所有关键部分