简体   繁体   English

INSERT有两个SELECT语句

[英]INSERT with two SELECT statements

Here is what I am currently trying but I am receiving an mySQL error: 这是我目前正在尝试但我收到一个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')"); 

I am able to complete an INSERT using a single SELECT statement however, not two. 我能够使用单个SELECT语句完成INSERT但不能两个。

The error I receive: 我收到的错误:

Query is invalid: You have an error in your SQL syntax; 查询无效:您的SQL语法中有错误; 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 查看与您的MySQL服务器版本对应的手册,以便在第1行附近使用'(SELECT tag_id FROM tag WHERE tag = '' OR tag = 'sports' OR tag = '')'附近使用正确的语法

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的值必须与列定义中的值数相匹配。

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. 请注意,如果为每个输入找到tag值,这将插入行,但我相信这就是您想要的。

You can use VALUES clause 您可以使用VALUES子句

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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