Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert values into a table using a SELECT subquery returning more than 1 value?

I am building a db with MySQL and would like to add several records at the same time, using a SELECT subquery to find values from a different table.

This query inserts a track into the tbl_track and checks if the release it belongs (album) (in tbl_release) has more than 1 format, CD or Vinyl. In this case, I have the album in Vinyl, Digital and CD formats.

When I use this following query I get an error "Subquery returns more than 1 row".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

INSERT INTO tbl_track (trackname, trackno, tracklength, releaseid) 
VALUES('Fluffy Tufts','2',3.6,(SELECT releaseid 
                               FROM tbl_release 
                               WHERE releasename = 'Victorialand' 
                                 AND releaseformat IN ('CD','V')));

Do I have to break this query into 2 queries, inserting 1 track for Vinyl format and another for CD format?

Thanks.

>Solution :

You can also remove the VALUES operator and use INSERT INTO ... SELECT, while moving your constants inside the query.

INSERT INTO tbl_track (trackname, trackno, tracklength, releaseid)
SELECT 'Fluffy Tufts', 
       '2',
       3.6, 
       releaseid 
FROM tbl_release 
WHERE releasename = 'Victorialand' AND releaseformat IN ('CD','V')));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading