SQL从表中插入表

时间:2013-07-24 12:04:24

标签: php mysql sql

DB 1

Table A
+-----+--------+---------------+
|  ID |  Price | Date          |
+-----+--------+---------------+
|  1  |    100 |  2013.07.07   |
+-----+--------+---------------+

Table B
+------+--------+-------------+-------+
|  ID  | Name   | Description | Stock |
+------+--------+-------------+-------+
| A-ID |  Name1 |  Good       |   100 |
+------+--------+-------------+-------+

从这些到

Table C
+------+--------+---------------+--------+
|  ID  | Name   | Description   | Date   |
+------+--------+---------------+--------+
| A-ID | B-Name | B-Description | A-Date |
+------+--------+---------------+--------+

Table D
+-------+------+-------+----------+
|  D_ID | ID   | Meta  | MetaValue|
+-------+------+-------+----------+
|  1    | A-ID | price | A-Price  |
+-------+------+-------+----------+
|  2    | A-ID | stock | B-Stock  |
+-------+------+-------+----------+

如何使用一个PhP代码从A和B填充C和D表? XS 在表A和表B中,我有15.000行 对于C需要为每个项目1行制作 对于D,需要为具有不同值的每个项目30行(在表A和表B中)

我以这种方式填写'表C'

INSERT INTO DB1.C (Name, Description) 
SELECT b.Products_Name, b.Description
FROM DB1.B AS b

UPDATE DB1.C c, DB1.A a
SET c.Date=a.Date
WHERE c.ID=a.ID'

2 个答案:

答案 0 :(得分:0)

插入表C

insert into TableCselect b.id,b.name,b.description,a.date 
from TableA a, TableB b 
where a.id = b.id

插入表Ep>

INSERT INTO TableD (ID,Meta, MetaValue) 
select id,'price',Price from TableA
Union
select id,'stock',Stock from TableB

答案 1 :(得分:0)

填写表格C:

INSERT INTO C (ID, Name, Description, Date)
SELECT A.ID, B.Name, B.Description, A.Date
FROM A INNER JOIN B ON A.ID = B.ID;

填写表D将是两个陈述:

INSERT INTO D (ID, Meta, MetaValue) /*assuming here, that D_ID is auto_increment...*/
SELECT A.ID, 'price', Price
FROM A
UNION ALL
SELECT A.ID, 'stock', B.Stock
FROM A INNER JOIN B ON A.ID = B.ID;