简体   繁体   English

MySQL 更新加入未按预期工作

[英]MySQL update join not working as expected

I'm using MySQL 5.1.41 on ubuntu 12.10 and MySQL Workbench.我在 ubuntu 12.10 和 MySQL 工作台上使用 MySQL 5.1.41。

I have 2 product tables, t1 and t2.我有 2 个产品表,t1 和 t2。 t1 is the live data and t2 is a imported data ready to be updated into t1 to update all the new product prices. t1 是实时数据,t2 是准备更新到 t1 以更新所有新产品价格的导入数据。 So I run:所以我跑:

SELECT * FROM t1
JOIN t2 ON t1.id = t2.id
WHERE t1.price != t2.price;

This returns 1201 records where the price is different and needs to be updated.这将返回 1201 条价格不同且需要更新的记录。 So I run:所以我跑:

UPDATE t1 JOIN t2 ON t1.id = t2.id
SET t1.price = t2.price
WHERE t1.price != t2.price;

This completes without error and reports 1143 row(s) affected, Rows matched: 1143 Changed: 1143 Warnings: 0这完成没有错误并报告 1143 行受影响,行匹配:1143 更改:1143 警告:0

So already something here is not right.所以这里已经有些不对劲了。 1201 records were different in the select query, but only 1143 changed using the same join and criteria? select 查询中的 1201 条记录不同,但使用相同的联接和条件仅更改了 1143 条?

Running the initial select query I'd expect to see 58 records that still had different prices.运行最初的 select 查询,我希望看到 58 条价格仍然不同的记录。 But when running it I get the same 1201 as I did initially.但是在运行它时,我得到了与最初相同的 1201。 It's as if the updates are not being committed.就好像没有提交更新一样。

Any ideas?有任何想法吗?

The number ( 1201 ) that your SELECT shows is not records of t1 but rows from the JOIN of two tables.您的SELECT显示的数字( 1201 )不是t1的记录,而是来自两个表的JOIN的行。 If the two id are not both UNIQUE or PRIMARY KEY s then this is expected.如果这两个id既不是UNIQUE也不是PRIMARY KEY ,那么这是预期的。 Some rows of t1 match multiple rows from t2 . t1的某些行与t2中的多行匹配。 But when the UPDATE is done they are only updated once (this is a MySQL "feature" or "bug" of UPDATE that checks WHERE conditions sequentially during an update statement.但是当UPDATE完成时,它们只更新一次(这是UPDATE的 MySQL “功能”或“错误”,它在更新语句期间按顺序检查WHERE条件。

Try this to see how many rows (of t1 ) should be updated:试试这个看看应该更新多少行(的t1 ):

SELECT * FROM t1
WHERE EXISTS
      ( SELECT *
        FROM t2
        WHERE t1.id = t2.id
          AND t1.price != t2.price
      );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM