在另一个基础上填充mysql表

时间:2013-06-15 09:06:52

标签: php mysql database compare

我有3个包含几个字段的mysql表。请参阅以下

--------  --------  --------
table 1 | table 2 | table 3
--------  --------  --------
a_id    | b_id    | email
                  | a_id
name    | status  | b_id
email_1 | date    | name
phone   | ref     | phone
address | email_2 | address
state   | from    | state
                  | status
                  | date
                  | ref
                  | from

email_1 email_2 完全相同。

我需要使用所有table1和table2数据填充table3字段。但我需要根据电子邮件将它们存储在一行中。所以他们看起来像是:

=================================================================================
                                   table 3
=================================================================================
email | a_id | b_id | name | phone | address | state | status | date | ref | from
------+------+------+------+-------+---------+-------+--------+------+-----+-----
a@x.co|  9   | 112  | John |  999  | xxxx    |   NY  |    0   | 15Jue| dave|  y
------+------+------+------+-------+---------+-------+--------+------+-----+-----
b@x.co|  6   | 338  | Sue  |  909  | xxxx    |   NY  |    1   | 12Jue| kell|  z
------+------+------+------+-------+---------+-------+--------+------+-----+-----
c@x.co|  3   | 152  | John |  679  | xxxx    |   NY  |    1   | 10Jue| lois|  g
------+------+------+------+-------+---------+-------+--------+------+-----+-----
d@x.co|  8   | 145  | John |  599  | xxxx    |   NY  |    0   | 8Jue | sue |  f

我无法弄清楚如何做到这一点。我正在使用核心php,mysql。有什么帮助吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

insert into table_3(`email`,`a_id`,`b_id`,`name`,`phone`,`address`,`state`,`status`,`date`,`ref`,`from`)
select `email_1`,`a_id`,`b_id`,`name`,`phone`,`address`,`state`,`status`,`date`,`ref`,`from`
from table_1,table_2
where email_1=email_2;

答案 1 :(得分:0)

我会在mysql中使用类似的东西:

insert into table_3
(
    `email`,
    `a_id`,
    `b_id`,
    `name`,
    `phone`,
    `address`,
    `state`,
    `status`,
    `date`,
    `ref`,
    `from`
)
select
    `a`.`email_1`,
    `a`.`a_id`,
    `b`.`b_id`,
    `a`.`name`,
    `a`.`phone`,
    `a`.`address`,
    `a`.`state`,
    `b`.`status`,
    `b`.`date`,
    `b`.`ref`,
    `b`.`from`
from 
    table_1 as `a`
    inner join
    table_2 as `b` on `a`.`email_1` = `b`.`email_2`

但你应该在MySQL insert syntax上阅读以了解它的力量,并在joining data上阅读:)