MySQL 您正在使用安全更新模式,并且您试图在没有 WHERE 的情况下更新 table

MySQL You are using safe update mode and you tried to update a table without a WHERE

我从 mySQL

收到了这条错误信息

"Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect. "

我使用的查询是这样的:

 UPDATE table1 a INNER JOIN table2 asa ON a.ID = asa.Table1Id SET a.ReferenceID = asa.ReferenceID WHERE a.ID > 0 AND asa.ID > 0 

我确实在两个表的 ID 上都有 where 子句,这些 ID 是两个表的主键。

禁用 SQL_SAFE_UPDATES 不是一个选项。

编辑:MySQL 版本为 v5.6

即使您使用的是 KEYS,我猜 KEYS 未正确使用MySQL documentation 说。

If this variable is enabled, UPDATE and DELETE statements that do not use a key in the WHERE clause or a LIMIT clause produce an error. This makes it possible to catch UPDATE and DELETE statements where keys are not used properly and that would probably change or delete a large number of rows.

即使在 WHERE 条件下,您的以下查询也会影响相同数量的行。我想 ID 的所有值都大于 0 对吗?如果是这样,那就是你出错的原因。

 UPDATE table1 a 
 INNER JOIN table2 asa 
 ON a.ID = asa.Table1Id 
 SET a.ReferenceID = asa.ReferenceID 
 --WHERE a.ID > 0 AND asa.ID > 0 

一种方法是建议SET SQL_SAFE_UPDATES=0;(禁用并尝试)。或者尝试改进 WHERE 条件。如果它是单个 table.

,您也可以使用 LIMIT

似乎 MySQL 5.6 在执行 UPDATE 语句和 JOIN

方面受到限制

所以,而不是

UPDATE table1 a
INNER JOIN table2 asa
ON a.ID = asa.Table1Id
SET a.ReferenceID = asa.ReferenceID
WHERE a.ID > 0 AND asa.ID > 0

您必须根据需要编写尽可能多的查询,例如:

UPDATE table1 a
SET a.ReferenceID = <The corresponding value in table 2>
WHERE a.ID = <The corresponding ID>

输入起来很烦人,可以使用动态 SQL 来构建更新查询:

SELECT CONCAT('UPDATE table1 a SET a.ReferenceID = ', asa.ReferenceID, ' WHERE a.ID = ', t.ID, ';')
FROM table1 t
INNER JOIN table2 asa
ON t.ID = asa.Table1Id;

例如:

架构(MySQL v5.6)

CREATE TABLE test
(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    foo VARCHAR(255)
);

CREATE TABLE test2
(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    id_test INT NOT NULL,
    foo VARCHAR(255),
    FOREIGN KEY (id_test) REFERENCES test(id)
);

INSERT INTO test (foo) VALUES ('hello'), ('world');

INSERT INTO test2 (id_test, foo) VALUES (1, 'bar'), (2, 'baz');

查询#1

SELECT CONCAT('UPDATE test t SET t.foo = ''', t2.foo, ''' WHERE t.id = ', t.id, ';') AS 'sql query'
FROM test t
INNER JOIN test2 t2
ON t.id = t2.id_test;

这输出:

UPDATE test t SET t.foo = 'bar' WHERE t.id = 1;
UPDATE test t SET t.foo = 'baz' WHERE t.id = 2;

输出现在可用于手动更新不同的行


View on DB Fiddle