【问题标题】:Selecting multiple unrelated data from two tables and insert into one table mysql从两个表中选择多个不相关的数据并插入到一个表中mysql
【发布时间】:2015-03-06 15:52:19
【问题描述】:

这是我的场景

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

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;

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

【问题讨论】:

  • 我到了下面,但在'from' INSERT INTO employee_permissions (empid,permid) (SELECT at2_permission.permission as permid FROM at2_permission where at2_permission.module='client') FROM at2_employee AS p INNER JOIN at2_permission c ON c.Id = p.Id INNER JOIN employee_permissions n ON n.Id = p.Id WHERE at2_employee.status='Act' and at2_employee.somestatus = 1;
  • 'Status' 是关键字,因此您可能需要更改字段名称

标签: mysql sql-insert insert-select


【解决方案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';

【讨论】:

    【解决方案2】:

    有点不清楚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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      相关资源
      最近更新 更多