从两个表中选择多个不相关的数据并插入一个表mysql

时间:2015-03-06 15:52:20

标签: mysql sql-insert insert-select

这是我的情景

我有一个包含以下字段的权限表。

id | module | permission

1  | client | add
2  | client | edit
3  | client | delete
4  | someth | edit
5  | someth | delete

员工表

id | status | somestatus
 1 |    act | 1
 2 |    den | 1
 3 |    act | 0
 4 |    den | 1
 5 |    act | 0
 6 |    act | 1

现在我需要做的是选择status =“act”和somestatus = 1的员工,并给予他们所有权限,其中module =“client”

所以表employee_permissions应该有这些行

id | empid | permid | permvalue
1  | 1     | 1      | 1
2  | 1     | 2      | 1
3  | 1     | 3      | 1
1  | 6     | 1      | 1
2  | 6     | 2      | 1
3  | 6     | 3      | 1

这是我试过的查询,我被困在这里

INSERT INTO at2_permission_employee (employee_id,permission_id) 
    SELECT at2_employee.employee_id as employee_id
         , (SELECT at2_permission.permission_id as permission_id 
            FROM at2_permission 
            where at2_permission.permission_module='client'
           ) 
    from  at2_employee  
    where at2_employee.employee_status='Active' 
      and at2_employee.employees_served_admin = 1;

我得到错误子查询返回多行,这对我来说很有意义。但是我不知道如何修改查询以便迭代子查询返回的行

2 个答案:

答案 0 :(得分:1)

如果我没错,就像这样:

INSERT INTO at2_permission_employee (employee_id, permission_id, permvalue)
SELECT 
  at2_employee.employee_id, 
  at2_permission.permission_id, 
  1  
FROM at2_permission cross join at2_employee
WHERE
  at2_employee.employee_status='Active' 
  and at2_employee.employees_served_admin = 1
  and at2_permission.permission_module='client';

答案 1 :(得分:0)

有点不清楚permvalue的值应来自何处,因此我对其进行了硬编码,并将permission.id用于idpermid,但此查询应该给你一个如何实现你想要的想法:

insert employee_permissions (id, empid, permid, permvalue)
select p.id, e.id, p.id, 1
from employee e, permissions p
where p.module = 'client' and e.status = 'act' and e.somestatus = 1;
相关问题