tags:

views:

51

answers:

1

Here is a sample query:

UPDATE `table1` 
   SET `table1`.`field1` = (SELECT COUNT(*) 
                              FROM `table2` 
                             WHERE `table2`.`field2` = `table1`.`field2`)

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

+2  A: 

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)

bemace