简体   繁体   中英

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

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.

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

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'))"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM