在表中插入行,其值为插入的每行不同的列

时间:2017-07-20 18:59:24

标签: mysql bulkinsert

我有这样的表:

CREATE TABLE test(id INT,product_id INT,sent_at datetime);
CREATE TABLE products(id INT);

我想创建一个这样的查询:

INSERT INTO test(product_id,sent_at)
    SELECT products.id as product_id,
    DATE_ADD(NOW(),INTERVAL 10 MINUTE) as sent_at
    FROM products;

我在products表中有1000行,我想为sent_at表中的每一行test列添加不同的值。 对于插入的sent_at表的每一行,products列应该再增加10分钟。 对于sent_at表格中的所有行,我不希望test列的值相同。

我不能使用程序。我正在使用MySQL 5.7。

请帮帮我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

非常适用于mysql

mysql> select * from products;
+------+
| id   |
+------+
|   23 |
+------+
1 row in set (0.00 sec)

mysql> INSERT INTO test(product_id,sent_at)
    ->     SELECT products.id as product_id,
    ->     DATE_ADD(NOW(),INTERVAL 10 MINUTE) as sent_at
    ->     FROM products;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from test;
+------+------------+---------------------+
| id   | product_id | sent_at             |
+------+------------+---------------------+
| NULL |         23 | 2017-07-20 19:26:36 |
+------+------------+---------------------+
1 row in set (0.00 sec)