Andreas
Andreas

Reputation: 2678

Insert data from another table with a loop in mysql

I could solve it with php or some other language but I am keen to learn more SQL.

Is there a way to solve this:

I have two tables (and I can't change the structure), one content with some data and the other content_info with some additional information. They are related that way: content.id = content_info.content_id.

What I would like to do: If there is no dataset in content_info but in content, I would like to copy it over, that at the end there are the same number of datasets in both tables. I tried it that way, but unfortunately it doesn't work:

...
BEGIN
  (SELECT id, ordering FROM content;)
  cont:LOOP
    @cid = SELECT content_id FROM content_info WHERE content_id = (id)
    IF @cid != (id) THEN
      INSERT INTO content_info SET content_id = (id), ordering = (ordering)
      ITERATE cont;
    END IF;
  END LOOP cont;
END
..

Has someone an idea, or isn't it possible at the end? Thanks in advance!

Upvotes: 9

Views: 15491

Answers (3)

user890904
user890904

Reputation:

I will give example for one field only, the id field. you can add other fields too:

insert into content_info(content_id)
select content.id
from content left outer join content_info
on (content.id=content_info.content_id)
where content_info.content_id is null

another way

insert into content_info(content_id)
select content.id
from content 
where not exists (
     select *
     from content_info
     where content_info.content_id  = content.id 
)

Upvotes: 2

Bill Karwin
Bill Karwin

Reputation: 562911

You can use INSERT IGNORE to insert new rows but do nothing if there's already a row in the table that would cause a duplicate entry error.

INSERT IGNORE INTO jos_content_frontpage (content_id, ordering)
SELECT id, ordering FROM jos_content

Upvotes: 13

Brent Baisley
Brent Baisley

Reputation: 12721

Seems like you are looking for the INSERT ... SELECT syntax. Any select can be inserted into a table provide you format the data to match the target table.

Also, your INSERT syntax is incorrect, looks like you are using the UPDATE syntax.

INSERT INTO table (field1, field2, field3) VALUES ('1','2','3');

INSERT INTO table (field1, field2, field3) SELECT field1, field2, field3 FROM ...

Upvotes: 3

Related Questions