简体   繁体   English

从 MySQL 中的同一个表中更新和选择

[英]Updating and Selecting from the same table in MySQL

Have a look at my sqlfiddle:看看我的 sqlfiddle:

http://sqlfiddle.com/#!9/60ffc4 (edited) http://sqlfiddle.com/#!9/60ffc4 (已编辑)

Code I am trying to execute:我试图执行的代码:

UPDATE inventory SET 
    product_name = CONCAT((SELECT name FROM products_and_packaging 
    WHERE product_id = (SELECT product_id FROM inventory 
    WHERE inventory_id = 196)), ' 100g Bunch')
WHERE inventory_id = 196

The result I am looking for is for product_name in the inventory table is renamed from NULL to "Flowers 100g Bunch" where product_id = 196.我正在寻找的结果是将库存表中的product_name从 NULL 重命名为“Flowers 100g Bunch”,其中 product_id = 196。

I get the #1093 error (You can't specify target table 'inventory' for update in FROM clause)我收到 #1093 错误(您不能在 FROM 子句中指定目标表 'inventory' 进行更新)

Note there are answers to similar questions here: You can't specify target table for update in FROM clause请注意这里有类似问题的答案: 您不能在 FROM 子句中指定要更新的目标表

MySQL Error 1093 - Can't specify target table for update in FROM clause MySQL 错误 1093 - 无法在 FROM 子句中指定要更新的目标表

However I tried to apply those solutions and came up with the exact same error due to the Inner Joins that were suggested.但是,由于建议的内部连接,我尝试应用这些解决方案并提出完全相同的错误。 Any pointers in the right direction would be great.任何朝着正确方向的指针都会很棒。

You don't need the nested subquery.您不需要嵌套子查询。 Just join the two tables as shown in the linked questions.只需连接两个表,如链接的问题所示。

UPDATE inventory AS i
JOIN products_and_packaging AS pp ON pp.product_id = i.product_id
SET i.product_name = CONCAT(pp.name, ' 100g Bunch')
WHERE i.inventory_id = 196

DEMO演示

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

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