MySQL - 如何将两个不同表中的数据合并到一个表中

时间:2011-09-01 12:38:40

标签: mysql

我有以下表格

ps_ext_mod     ps_customer    ps_order_detail
---------      -----------    ---------------
id             .....          ..... 
cust      <==  email          .....
prod                  <==     product_reference

我需要将email的数据添加到cust,将product_reference的数据添加到prod。 id是自动增量。

希望看起来应该是这样的:

ps_ext_mod
-----------
id | cust   | product
---------------------
1  | a@a.com | prod1
2  | a@a.com | prod2
3  | b@b.com | prod1
4  | c@c.com | prod3

1 个答案:

答案 0 :(得分:1)

INSERT INTO ps_ext_mod (email, product) SELECT
   c.email, d.product
   FROM ps_customer c
   INNER JOIN ps_order_detail d ON (d.customer_id = c.id) 

您需要稍微调整连接条件以匹配您的数据库结构 如果两个表不相关,则使用如下查询:

INSERT INTO ps_ext_mod (email, product) SELECT
   c.email, d.product
   FROM ps_customer c
   CROSS JOIN ps_order_detail