簡體   English   中英

從一個表中獲取所有ID,然后根據該表在另一個表中插入值

[英]Get all ID's from one table and insert values in another table based on it

我有兩個表:

表1:公司(id,名稱)表2:假期(id,companyId,名稱)

當前公司表中有數據,但節假日沒有。 我想遍歷所有公司,獲取其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 |

假設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);

您需要Companies表的自聯接和迭代邏輯來為Holidays生成id列值。 因此,請考慮使用:

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;

演示版

我想你要:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM