Solved

MySQL Insert

Posted on 2011-03-04
2
387 Views
Last Modified: 2012-05-11
I am have a brain fart trying to figure out the logic to perform a particular query. Looking for assistance!

The following table is used to store all the items that a child has in his chest. As you can see, a child can have multiple items.

child_id     item_id     quantity
1               1              1
2               1              1
2               1              1
2               4              1
2               4              1
3               8              1
3               9              1
4               2              1

What I am trying to do is give every child item #8 that don't already have it. My first attempt at this query is show in the code section below. However, this doesn't work very well, as it will still return records if the child has other options.
INSERT child_items (child_id, item_id, quantity)
SELECT DISTINCT child_id, 8, 1 
FROM child_items WHERE item_id != 8;

Open in new window

0
Comment
Question by:plecostomus
2 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 35038412
what about:
INSERT child_items (child_id, item_id, quantity)
SELECT child_id, 8, 1 
FROM child_items 
GROUP BY child_id
HAVING MAX(CASE WHEN item_id = 8 THEN 1 ELSE 0 END) = 0

Open in new window


or:
INSERT child_items (child_id, item_id, quantity)
SELECT child_id, 8, 1 
FROM child_items i
WHERE NOT EXISTS( SELECT NULL FROM child_items o WHERE o.child_id = i.child_id AND o.item_id = 8 )
GROUP BY child_id

Open in new window


however, not sure if it will actually work in MySQL, you might run into the issue that you cannot select from the same table you do the insert into,
so you might need to run the insert into a temp table first ...

0
 

Author Closing Comment

by:plecostomus
ID: 35038632
Worked perfectly... MySQL 5.0/5.1 allows you to insert into itself from itself.
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating and Managing Databases with phpMyAdmin in cPanel.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo‚Ķ

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question