【问题标题】:select multiple column from one table and insert into another as rows从一个表中选择多列并作为行插入另一个表
【发布时间】:2014-11-14 16:51:40
【问题描述】:

我有两个表用户和电子邮件:

USER
+--------+-------+--------+--------+
| id (PK)| email | email2 | email3 |
+--------+-------+--------+--------+

EMAIL
+---------+--------------+---------------+
| id (PK) | user_id (FK) | email_address | 
+---------+--------------+---------------+

我需要从用户表中选择电子邮件并将它们作为行插入到电子邮件表中。

【问题讨论】:

  • 向我们展示您到目前为止所做的尝试以及您面临的任何问题
  • 您说的是“email2、email3 等”。 - 那是多少个电子邮件列?

标签: mysql sql


【解决方案1】:

如果您的电子邮件表 id 有身份,我会这样做

INSERT INTO email (userid,email_address)
SELECT id, email  FROM user
UNION SELECT id, email2  FROM user
UNION SELECT id, email3 FROM user

【讨论】:

  • 另外,如果您在 email2、email3 等中有 null 值。我会将 email 设置为非 null(实际上您应该将 userid&emailaddress 设为复合键)。这样您就不会在新表中插入空电子邮件。
  • @boisvert 好点。拥有复合键不仅可以过滤掉空值,还可以确保处理冗余
【解决方案2】:

使用联合来这样做。

insert into email values(
select user_id, email from user
union
select user_id, email1 from user
union
select user_id, email2 from user
union
select user_id, email2 from user
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多