Link to home
Start Free TrialLog in
Avatar of plecostomus
plecostomusFlag for Canada

asked on

Insert into Table from Another Table with Conditions

I am struggling trying to figure out a way to insert records into a table from another... Currently, I have the following two tables (attached as code)...

The first table contains a list of pets "owned" by a particular person and the second contains items owned by the pet. What I am trying to do is give all the pets 1 of item 10 and 1 of item 11 if the pets type is 10.

I tried this query, but it doesn't work.

INSERT pet_items (person_id, pet_item_id, quantity) SELECT DISTINCT p.person_id, 10,1 FROM pets p JOIN pet_items pi ON pi.person_id = p.person_id WHERE p.type = 10 AND pi.pet_item != 15;

 
CREATE TABLE `pets` (
  `pet_id` int(11) NOT NULL,
  `person_id` int(11) NOT NULL,
  `pet_name` varchar(30) DEFAULT NULL,
  `pet_type` smallint(6) NOT NULL,
  PRIMARY KEY (`pet_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

CREATE TABLE `pet_items` (
  `person_id` int(11) NOT NULL,
  `item_id` int(11) NOT NULL,
  `quantity` smallint(6) NOT NULL,
  PRIMARY KEY (`person_id`,`item_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Steve Tempest
Steve Tempest
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial