2

Is there a way to insert rows based on a query with multiple rows result?

Something like this:

For each row in (select brand, date from table_A where ...) insert into table_B (field_1, field_2) VALUES (table_A.brand, table_A.date);

Using SQLite3 (preferred) / MySQL.

Thanks

Here's what I've tried:

insert into media_tags (fk_id_media, fk_id_tag) VALUES ( (select id_media from media where fullpath like "%C32%") , (select id_tag from tags where tagname='digital') )

1 Answer 1

3

Just do:

insert into table_B (field_1, field_2)
select brand, date
from table_A
where...

This will insert in table_B all the rows that are returned from the SELECT.

In your case you could change::

insert into media_tags (fk_id_media, fk_id_tag)
values (
  (
    select id_media
    from media
    where fullpath like "%C32%"
    ), (
    select id_tag
    from tags
    where tagname = 'digital'
    )
  )

to

insert into media_tags (fk_id_media, fk_id_tag)
select id_media, (
    select id_tag
    from tags
    where tagname = 'digital'
    )
from media
where fullpath like "%C32%"

This will although only give you variable values in fk_id_media. fk_id_tag will always be the same, but it looks that you want it that way.

Sign up to request clarification or add additional context in comments.

6 Comments

@Azevedo. Yes it works. In both sqlite and mysql: sqlite demo, mysql demo. INSERT .. Values() lets you insert only one row at a time, to make it work for multiple rows this is the way you do it.
Well, it works with one select, but if you use two selects it won't
Sure. That will not work, you'll have to use a way of JOINING the two selects and return the data you want in only one select. Can you show the table schemmas of the tables where you are trying to do this ?
Tricky. Works but I still don't get it why This will although only give you variable values in fk_id_media. fk_id_tag will always be the same. If fk_id_tag would have to change then I'd have to look for another solution then.
maybe what is keeping id_tag fixed is where tagname = 'digital'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.