3

这是我目前正在尝试的,但我收到了一个 mySQL 错误:

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

但是,我可以INSERT使用单个SELECT语句完成一个,而不是两个。

我收到的错误:

查询无效:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以'(SELECT tag_id FROM tag WHERE tag = '' OR tag = 'sports' OR tag = '')'在第 1 行附近使用正确的语法

4

3 回答 3

3

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.

于 2013-02-14T03:58:23.550 回答
1

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

于 2013-02-14T03:58:30.413 回答
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'))"); 
于 2013-02-14T04:03:17.997 回答