Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT with two SELECT statements

Tags:

php

mysql

Here is what I am currently trying but I am receiving an mySQL error:

mysql_query ("INSERT INTO profile_tag (profile_id, tag_id) 
(SELECT profile_id FROM profile WHERE username = '$username'), 
(SELECT tag_id FROM  tag WHERE  tag = '$music' OR tag = '$sports' OR tag = '$tech')"); 

I am able to complete an INSERT using a single SELECT statement however, not two.

The error I receive:

Query is invalid: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT tag_id FROM tag WHERE tag = '' OR tag = 'sports' OR tag = '')' at line 1

like image 484
rp7 Avatar asked Jan 30 '26 01:01

rp7


1 Answers

Much like the error says, the syntax is incorrect. The values of the insert has to match the number of values in the column definition.

INSERT INTO profile_tag (profile_id, tag_id)
SELECT
    profile_id, tag_id
FROM
    profile
    CROSS JOIN tag
WHERE
    username = ?
    AND tag IN (?, ?, ?)

Note that this will insert multiple rows if a tag value is found for each of the inputs, but I believe that is what you want.

like image 184
Explosion Pills Avatar answered Jan 31 '26 15:01

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!