我不认为这是可能的,但我想我会检查它是否可行,如果不行,请寻求最有效的替代方案。
目标:
使用带有 Inner Join
和 WHERE
table_1
和 table_2
目前我有:
UPDATE table_1
JOIN table_2 ON table_1.user_id= table_2.user_id
SET
table_1.value = 9,
table_2.value_fan = 43
WHERE
table_1.user_id = 1 AND table_2.fan_id =1
这根据 WHERE
条件正确更新了 table_2
,但是所有条目都在 table_1
中更新,其中 table_1.user_id = 1
...忽略条件 table_2.fan_id = 1
编辑 对不起,我应该更清楚,我上面有错字,现在更正了......下面还有一个SQLFiddle的链接
http://sqlfiddle.com/#!2/58d7b/1
我希望您能看到 Table_2_winnings 已正确更新,只有一个用户 James 获得了任何奖金(因为他有 city_id =1 和 group_id =1)。但是,group_id = 1 中 table_1 中的所有用户都已更新。我只想更新 James 的地方...
最佳答案
ON table_1.city= table_2.city
是查询中唯一的连接过滤器。由于 city 可以在两个表中多次出现,因此内部连接就像交叉连接一样。参见 this fiddle . 所以为了获得所需的列只添加了一个连接过滤器
and table_1.user = table_2.user;
因此您的更新查询将是:
UPDATE table_1,table_2
SET
table_1.table_1_winnings = 6,
table_2.table_2_winnings = 43
WHERE
table_1.city = 1 AND table_2.city_id =1
and table_1.city= table_2.city
and table_1.user = table_2.user;
关于mysql - 使用 INNER JOIN 和 WHERE 更新 MySQL 中的两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17663533/