0

I have a table called users and I want to get all users and for each user, create a row in a table called products. Is it possible to do this with a query?

4

2 回答 2

3

根据各自的表结构,一条INSERT INTO ... SELECT语句应该起作用:

INSERT INTO `products`
SELECT 1 FROM `users`

如果 products 表有一个int- 列,这将插入与表中的用户一样多的users列。

您只需调整SELECT语句以在新表中生成所需的值。

示例小提琴

于 2013-07-29T15:18:11.263 回答
1

您可以插入 select 语句的结果,如下所示:

INSERT INTO products (field1,field2...) SELECT 
    something_that_goes_into_products_field1,
    something_that_goes_into_products_field2,
    ....
FROM users
WHERE users_that_have_to_be_inserted

如果产品有一个自动增量字段,您可能应该从字段列表中省略它。

于 2013-07-29T15:20:30.817 回答