表1:mydata_table
多列。但我想获取3列不同的记录。
Email_Office | Email_Personal1 | Email_Personal2
表2:unique_emails
只有3列。 Email_Office | Email_Personal1 | Email_Personal2
我为表2的所有三列尝试了此代码,以便从每列插入不同的记录。
insert into unique_emails
(email_personal1)
select distinct email_personal1
from mydata_table
where Email_Personal1!=""
它插入了记录,但问题是如果email_office列中有100行,email_personal1中有300行,那么它将显示前100行包含email_office,其余两列为空,然后从第101行开始,它将显示email_personal1的记录剩下的两列是空的。我想将所有行插入在一起。我怎么能这样做?
答案 0 :(得分:1)
如果要插入唯一的电子邮件三元组,则应使用
insert into unique_emails
(email_office, email_personal1, email_personal2)
select distinct email_office, email_personal1, email_personal2
from mydata_table
where email_office!="" OR Email_Personal1!="" OR Email_Personal2!=""
但在这种情况下,某些电子邮件可能会在表unique_emails中多次出现。
假设表1包含记录:
Email_Office | Email_Personal1 | Email_Personal2
------------------------------------------------
a@a.com b@b.com c@c.com
a@a.com b@b.com c@c.com
a@a.com b@b.com e@e.com
a@a.com c@c.com NULL
a@a.com d@d.com e@e.com
然后结果表2
Email_Office | Email_Personal1 | Email_Personal2
------------------------------------------------
a@a.com b@b.com c@c.com
c@c.com e@e.com
d@d.com
<强> UPD。强> 试试这个:(SQL Fiddle)
insert into unique_emails
(email_office, email_personal1, email_personal2)
select b.email_office, c.email_personal1, d.email_personal2
from (
select @i := @i + 1 AS pos from mydata_table, (select @i := 0) r) a
left join (
select t.*, @j := @j + 1 AS pos
from (select distinct email_office from mydata_table where email_office!="") t,
(select @j := 0) r) b on b.pos = a.pos
left join (
select t.*, @k := @k + 1 AS pos
from (select distinct email_personal1 from mydata_table where email_personal1!="") t,
(select @k := 0) r) c on c.pos = a.pos
left join (
select t.*, @l := @l + 1 AS pos
from (select distinct email_personal2 from mydata_table where email_personal2!="") t,
(select @l := 0) r) d on d.pos = a.pos
where b.email_office is not null or c.email_personal1 is not null or d.email_personal2 is not null
答案 1 :(得分:1)
尝试为需要唯一的列创建唯一索引,并使用@Sergey提出的第一个使用ignore的SQL:
INSERT IGNORE INTO
unique_emails
(email_office, email_personal1, email_personal2)
SELECT DISTINCT
email_office,
email_personal1,
email_personal2
FROM
mydata_table
WHERE
email_office!=""
OR Email_Personal1!=""
OR Email_Personal2!=""