【问题标题】:Insert two Records in new mysql table for each record in another table为另一个表中的每条记录在新的 mysql 表中插入两条记录
【发布时间】:2023-02-04 06:20:44
【问题描述】:

我需要在新的 mysql 表中为另一个表中的每条记录插入两条记录 例子:

表格1

id, name 
1, Patrick
2, John

我想为第二个表中的每条记录插入最喜欢的网站,每条记录都应该默认有 facebook 和 google

第二个表应该是这样的: 表2

table1_id, site
1, facebook
1, google
2, facebook
2, google

【问题讨论】:

    标签: mysql sql select sql-insert


    【解决方案1】:

    我们可以将原始表与带有 cross join 的固定行列表相乘:

    insert into table2 (table1_id, site)
    select t1.id, s.site
    from table1 t1
    cross join (select 'google' site union all select 'facebook') s
    

    在最近的 MySQL 版本 (>= 8.0.19) 中,the VALUES statement 使语法更简洁:

    insert into table2 (table1_id, site)
    select t1.id, s.site
    from table1 t1
    cross join ( values row('google'), row('facebook') ) s(site) 
    

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 2015-01-26
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多