开发者

UPDATE and SELECT - Using the table called from update in the select query

开发者 https://www.devze.com 2023-01-20 14:49 出处:网络
Here is a sample query: UPDATE `table1` SET `table1`.`field1` = (SELECT COUNT(*) FROM `table2` WHERE `table2`.`field2` = `table1`.`fie开发者_StackOverflowld2`)

Here is a sample query:

UPDATE `table1` 
   SET `table1`.`field1` = (SELECT COUNT(*) 
                              FROM `table2` 
                             WHERE `table2`.`field2` = `table1`.`fie开发者_StackOverflowld2`)

MySQL gives me an error message that table1.field2 does not found. Please advice


I think it's easier to understand with a less abstract example.

materials table

CREATE TABLE IF NOT EXISTS `materials` (
  `material_id` int(11) NOT NULL auto_increment,
  `name` varchar(20) NOT NULL,
  `qty` tinyint(4) default NULL,
  PRIMARY KEY  (`material_id`)
)

part_materials table

CREATE TABLE IF NOT EXISTS `parts` (
  `part_id` int(11) NOT NULL auto_increment,
  `material_id` varchar(30) NOT NULL,
  PRIMARY KEY  (`part_id`,`material_id`)
)

To update materials.qty with number of parts using that material:

update materials set qty=(select count(*) from part_materials where material_id=materials.material_id)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号