rp7
rp7

Reputation: 137

INSERT with two SELECT statements

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

Upvotes: 3

Views: 314

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

You can use VALUES clause

insert into profile_tag(user_id, tag_id) values
((select id from users where username = 'alice'),
 (select id from tags where tag = 'music'));

http://sqlfiddle.com/#!2/76439/1/0

Upvotes: 1

vearutop
vearutop

Reputation: 4062

mysql_query ("INSERT INTO profile_tag (profile_id, tag_id) 
(SELECT profile.profile_id, tag.tag_id FROM profile LEFT JOIN tag ON 1 WHERE profile.username = '$username' AND tag.tag IN ('$music', '$sports', '$tech'))"); 

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

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.

Upvotes: 3

Related Questions