我有表users
(id
,email
),permissions
(id
,description
)和users_permissions
( user_id
,permission_id
,created
)之间存在多对多关系。
我需要从用户那里选择一些电子邮件,并向他分配表permissions
中没有的所有权限。
现在,我尝试分配至少所有权限,但出现错误
子查询返回1行以上
我的查询:
insert into `users_permissions` (`user_id`, `permission_id`, `created`)
select
(select `id` from `users` where `email` = 'user-abuser@gmail.com') as `user_id`,
(select `id` from `permissions`) as `permission_id`,
now() as `created`;
答案 0 :(得分:2)
如果子查询(在SELECT
内部)返回多行,则MySQL不喜欢它。
满足要求的另一种方法是在派生表(CROSS JOIN
子句中的子查询)之间使用FROM
:
INSERT INTO `users_permissions` (`user_id`, `permission_id`, `created`)
SELECT
u.id,
p.id,
NOW()
FROM
users AS u
CROSS JOIN permissions AS p
WHERE u.email = 'user-abuser@gmail.com'