【问题标题】:How can I easily INSERT data in a table from multiple columns from another table?我怎样才能轻松地从另一个表的多个列中插入数据到一个表中?
【发布时间】:2022-12-07 13:50:29
【问题描述】:

我想从公司表中获取所有电话号码,并将其放入专用电话号码表中,是否有一种简单的方法可以仅使用(如果可能)一个查询来执行此操作?

公司表中的示例数据(tel3 和 tel4 可能有电话号码):

id tel tel2 tel3 tel4
1 32772373636 32724522341
2 32783675626
3 32968381949

phonenrs 表中的预期示例输出:

id company_id phonenr
1 1 32772373636
2 1 32724522341
3 2 32783675626
4 3 32968381949

【问题讨论】:

  • 不确定降价是否有误?在问题创建页面上,它为我正确显示了它
  • 我已经修复了你的降价,只要确保在桌子前留出额外的空间
  • 使用 UNION 时要小心,因为它不支持有效的 ORDER BY。

标签: mysql sql sql-insert


【解决方案1】:

您可以使用 union alls 电话号码查询中的插入选择语句:

INSERT INTO numbers (company_id, phonenr)
SELECT it, tel FROM numbers WHERE tel IS NOT NULL
UNION ALL
SELECT it, tel2 FROM numbers WHERE tel2 IS NOT NULL
UNION ALL
SELECT it, tel3 FROM numbers WHERE tel3 IS NOT NULL
UNION ALL
SELECT it, tel4 FROM numbers WHERE tel4 IS NOT NULL

【讨论】:

    【解决方案2】:

    得到精确的匹配您的预期输出,首先我们需要为您的新 id 列添加一个行 ID。然后,为了确保 tel > tel2 > tel3 > tel4 的排序优先级,我们可以执行一个技巧来做到这一点。这是在工作台中编写和测试的代码:

    select @row_id:=@row_id+1 as id, id as company_id,trim(leading '0' from phone ) as phonenr
    from
    (select id,ifnull(concat('000',tel),1) as phone from companies
    union all
    select id,ifnull(concat('00',tel2),1) from companies
    union all
    select id,ifnull(concat('0',tel3),1) from companies
    union all
    select id,ifnull(tel4,1) from companies
    ) t1, 
    (select @row_id:=0) t2
    where phone !=1
    order by company_id,phone
    ;
    -- result:
    # id, company_id, phonenr
    1, 1, 32772373636
    2, 1, 32724522341
    3, 2, 32783675626
    4, 3, 32968381949
    

    如您所见,通过在电话中添加不同数量的前导零,我们可以操纵排序优先级。没有它,第一行我得到 32724522341 而不是 32772373636。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多