从一个表中获取所有ID,然后根据该表在另一个表中插入值

时间:2019-06-30 07:54:39

标签: mysql sql sql-insert

我有两个表:

表1:公司(编号,名称) 表2:假期(id,companyId,name)

当前“公司”表中有数据,但假期没有。我想遍历所有公司,获取其ID并在假期为每个公司插入两条记录。因此,这将在之前和之后:

之前:

Companies
| id | name  |
|  0 | test1 |
|  1 | test2 |

节假日: Empty table

之后:

Companies
| id | name  |
|  0 | test1 |
|  1 | test2 |
Holidays:
| id | companyId | name     | 
|  0 |         0 | holiday1 |
|  1 |         0 | holiday2 |
|  2 |         1 | holiday1 |
|  3 |         1 | holiday2 |

3 个答案:

答案 0 :(得分:1)

假设Holidays.id设置为自动递增:

insert into Holidays (select id as companyId, 'holiday1' as name from Companies);
insert into Holidays (select id as companyId, 'holiday2' as name from Companies);

答案 1 :(得分:1)

您需要Companies表的自联接和迭代逻辑才能为id生成Holidays列值。因此,请考虑使用:

insert into Holidays(id,company_id,name)
select @rn := @rn + 1, c1.id, concat('Holiday',(c1.id+1))
  from Companies c1
  join Companies c2
  join (select @rn := -1) as q_iter;

Demo

答案 2 :(得分:0)

我想你想要

insert into holidays (companyId, name)
    select c.companyId, h.name
    from companies c cross join
         (select 1 as ord, 'holiday1' as name union all
          select 2 as ord, 'holiday2'
         ) h
    order by c.companyId, h.ord;

这假设holidays.id是自动递增的列。如果没有,则应使其成为一体。但是,如果没有,则可以使用row_number()

insert into holidays (id, companyId, name)
    select row_number() over (order by c.companyId, h.ord),
           c.companyId, h.name
    from companies c cross join
         (select 1 as ord, 'holiday1' as name union all
          select 2 as ord, 'holiday2'
         ) h
    order by c.companyId, h.ord;

或参数:

insert into holidays (id, companyId, name)
    select (@rn := @rn + 1) as id,
           c.companyId, h.name
    from companies c cross join
         (select 1 as ord, 'holiday1' as name union all
          select 2 as ord, 'holiday2'
         ) h cross join
         (select @rn := 0) params
    order by c.companyId, h.ord;