Reputation: 1039
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.
Basically the senario is:
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
I need to insert the 3 lines from table1 into 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).
YYYYYY for each line is the '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
Upvotes: 0
Views: 1688
Reputation: 5428
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
Upvotes: 1
Reputation: 247670
You can use 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.
Upvotes: 2