[英]mysql - 'Subquery returns more than 1 row' when INSERT multiple values from two different tables into a 'bridge table'
I have 3 tables:我有 3 张桌子:
I'm trying to execute this query:我正在尝试执行此查询:
INSERT INTO `db`.`users_roles` (`user_id`, `role_id`)
VALUES ((SELECT id FROM `db`.`users` WHERE username like '%@gmail.com'), (Select id from roles where authority="can_view"));
Since there are hundreds of user_id
with the username like %gmail.com, I'm getting the error " Subquery returns more than 1 row ".由于有数百个用户名(如 %gmail.com)的
user_id
,我收到错误“子查询返回超过 1 行”。 Also, there's only one authority, that's why i used the = operator.此外,只有一个权限,这就是我使用 = 运算符的原因。 I'm aware I should use the
IN
operator when working with multiple values, but I don't seem to know how to properly write this query with the first SELECT
.我知道在处理多个值时应该使用
IN
运算符,但我似乎不知道如何使用第一个SELECT
正确编写此查询。
How can i solve this problem?我怎么解决这个问题? Help!
帮助!
Just use insert. . . select
只需使用
insert. . . select
insert. . . select
insert. . . select
: insert. . . select
:
INSERT INTO db.users_roles (user_id, role_id)
SELECT u.id, r.id
FROM db.users u JOIN
roles r
ON u.username like '%@gmail.com' AND
r.authority = 'can_view';
Looks like you are trying to give can_view
permission to existing users with a gmail account.看起来您正在尝试向具有 gmail 帐户的现有用户授予
can_view
权限。 If that is the case, there is no need for you to select from the roles
table.如果是这种情况,则无需从
roles
表中输入 select。 Just run the roles
table query to get the can_view
permission ID and then you can just hard code that into the query like so:只需运行
roles
表查询以获取can_view
权限 ID,然后您可以将其硬编码到查询中,如下所示:
INSERT INTO db.users_roles (user_id, role_id) SELECT id, RoleIDFromPreviousQueryHere FROM db.users WHERE username like '%@gmail.com'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.