mysql - 两张表的SQL更新语句

标签 mysql sql

我使用的是 MySQL 5.5,我有两个表,inventory_items 和 menu_items。它们都有一个字符串 bin_number 和一个整数 location_id。

menu_items
invetory_item_id | location_id | bin_number


inventory_items
id | location_id | bin_number

我想将 menu_items inventory_item_id 更新为 inventory_items 表的 ID,它们在 bin_number 和 location_id 上是相等的。我可以像这样经历每一个:

update menu_items set inventory_item_id=(select id from inventory_items where 
bin_number='7060'  and location_id=37) where bin_number='7060'  and location_id=37;

有没有办法说将所有 menu_items 更新为 menu_items 和 inventory_items 之间的 bin_number 和 location_id 相同?

最佳答案

您可以在UPDATE 中使用JOIN:

 UPDATE menu_items mi 
     JOIN inventory_items ii ON mi.bin_number=ii.bin_number 
         AND mi.location_id=ii.location_id
 SET mi.inventory_item_id = ii.id 

关于mysql - 两张表的SQL更新语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25944821/

相关文章:

mysql - 数组 在mysql程序中?

mysql - 3 表 JOIN 与 group by 不起作用

sql - 定义数据库的表结构?

javascript - 使用API​​数据更有效的方法是什么?

mysql - ORDER BY 子句使查询变慢,尽管结果集很小

php - 我想从 mysql 数据库中获取行,并按附近和距离限制进行过滤

MySQL建表错误

MySQL 使用 IN 和 LIKE 通配符查找数据

SQL获取每行的最大列值

mysql - SQL语法限制1个错误