简体   繁体   English

两个表的SQL更新语句

[英]SQL update statement for two tables

I am using MySQL 5.5 and I have two tables, inventory_items and menu_items.我使用的是 MySQL 5.5,我有两个表,inventory_items 和 menu_items。 They both have a bin_number which is a string and a location_id which is an integer.它们都有一个 bin_number 是一个字符串,一个 location_id 是一个整数。

menu_items
invetory_item_id | location_id | bin_number


inventory_items
id | location_id | bin_number

I'd like to update the menu_items inventory_item_id to the id of the inventory_items table where they are equal on bin_number and location_id.我想将 menu_items inventory_item_id 更新为 inventory_items 表的 id,其中它们在 bin_number 和 location_id 上相等。 I could go through each like this:我可以像这样经历每一个:

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;

Is there a way to say update all menu_items to where the bin_number and location_id are the same between menu_items and inventory_items?有没有办法说将所有 menu_items 更新到 menu_items 和 inventory_items 之间 bin_number 和 location_id 相同的位置?

You can use a JOIN in your UPDATE :您可以在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 

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

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