简体   繁体   English

MSQL从带有子查询和1个值的select语句中插入多行

[英]MSQL Insert multiple row from select statment with subquery and 1 value

I want insert new data in my table with condition that i get from subquery here sample of table :我想在我的表中插入新数据,条件是我从这里的表示例中获得的子查询:

permission允许

role_id     permission_id
   1              1
   1              2
   1              3
   2              1
   2              3
   3              1
   3              2
   4              1

So, lets say role_id is a group of id that have more than 1 permission id that connected.因此,可以说 role_id 是一组 id,它具有超过 1 个连接的权限 id。 So i would like to insert new data that role_id doesn't have permission id 2. which are role_id 2 and 4所以我想插入新数据,role_id 没有权限 id 2。它们是 role_id 2 和 4

i would like to run this query :我想运行这个查询:

INSERT INTO PERMISSION
VALUES ('2', '2')
VALUES ('4', '2');

in 1 query, i have try to run this query :在 1 个查询中,我尝试运行此查询:

INSERT INTO permission(role_id, permission_id)
VALUES( 
    (select distinct(role_id) from role_permission rp2 
    where role_id NOT IN (
    select role_id from role_permission rp
    where permission_id = 2)),
    2);

but the result is it always get error :但结果是它总是出错:

SQL Error [1242] [21000]: Subquery returns more than 1 row

is there any way for inserting multiple query mix with 1 value using mysql ?有什么方法可以使用 mysql 插入具有 1 个值的多个查询组合吗?

Your first query is missing a comma and repeats VALUES .您的第一个查询缺少逗号并重复VALUES I also recommend listing the columns我还建议列出列

INSERT INTO PERMISSION (role_id, permission_id)
    VALUES ('2', '2'),
           ('4', '2');

Note that ids are usually numbers.请注意,id 通常是数字。 If that is the case, then remove the single quotes.如果是这种情况,则删除单引号。

For the second query, use INSERT . . . SELECT对于第二个查询,使用INSERT . . . SELECT INSERT . . . SELECT INSERT . . . SELECT " INSERT . . . SELECT

INSERT INTO permission (role_id, permission_id)
    select rp.role_id, 2
    from role_permission rp
    group by rp.role_id
    having sum(rp.permission_id = 2) = 0;

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

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