[英]INSERT into MySQL table from another table
Working on a MySQL DB, I have a few hundred (couple thousand) rows I need to enter into a table, where part of the data is coming from a second table. 在MySQL DB上工作时,我需要进入几百(成千上万)行到一个表中,其中部分数据来自第二个表。
Basically the senario is: 基本上,senario是:
I have a table which carries values exampled below: 我有一个表,其中包含以下示例的值:
SELECT DISTINCT object_id FROM table1 WHERE reference = 'ABC123';
returns say 3 values: 12345 67890 66699 返回说3个值:12345 67890 66699
I need to insert the 3 lines from table1 into table2: 我需要将table1中的3行插入table2中:
INSERT INTO table2
(tbl2_unique_id, tbl1_obj_id,object_date)
VALUES
(XXXXXX,YYYYYY,NOW());
But... 但...
XXXXXX is an incremental number (I can't make it auto_incremental) starting from '475611' (this just happens to be the last value in table2). XXXXXX是从“ 475611”开始的增量数字(我不能使其为auto_incremental)(这恰好是table2中的最后一个值)。
YYYYYY for each line is the '12345',67890','66699' 每行的YYYYYY为'12345',67890','66699'
giving you 给你
table2
---------------------------------
tbl2_unique_id, tbl1_obj_id, object_date
---------------------------------
475611 , 12345, YYYY-MM-DD HH:MM:SS
475612 , 67890, YYYY-MM-DD HH:MM:SS
475613 , 66699, YYYY-MM-DD HH:MM:SS
Any advice? 有什么建议吗?
Cheers in advance 提前加油
KS 堪萨斯州
You can use INSERT INTO...SELECT...FROM
: 您可以使用INSERT INTO...SELECT...FROM
:
INSERT INTO table2 (tbl1_obj_id,object_date)
select DISTINCT object_id, NOW()
FROM table1
WHERE reference = 'ABC123'
You will notice that I excluded the tbl2_unique_id
since it is auto increment, you can exclude that since you will not have a value until it is inserted. 您会注意到,由于tbl2_unique_id
是自动递增的,因此我将其排除在外,因此您可以排除tbl2_unique_id
,因为直到插入它之前您都没有值。
Example: 例:
INSERT INTO orders (customer_cust_id, orderdatetime, message, taxrate, shippingprice)
SELECT '1', NOW(), null, taxrate, shippingprice FROM customer
WHERE cust_id='1';
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html http://dev.mysql.com/doc/refman/5.1/zh-CN/insert-select.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.