简体   繁体   English

从一个表到另一个具有相同ID号码的值插入

[英]INSERT values from one table to another with the same ID NUMBERS

I have two tables in the same database. 我在同一数据库中有两个表。 I would like to pass some information from one table to the other. 我想将一些信息从一个表传递到另一个表。

In the first table "products", I have products_id, products_length, products_width and products_height and I would like to pass all the information from that table to a second one called "product". 在第一个表“ products”中,我有products_id,products_length,products_width和products_height,我想将所有信息从该表传递给第二个“ product”。

The second table "product" has the following columns product_id, lenght, width and height. 第二个表“产品”具有以下列product_id,长度,宽度和高度。

In both tables the products are the same ones and they have the same ID NUMBER. 在两个表中,产品都是相同的,并且具有相同的ID号。

I just need help on how to INSERT the values from "products" to "product". 我只需要有关如何将值从“产品”插入“产品”的帮助。

Try this: 尝试这个:

CREATE TABLE product LIKE products;
INSERT INTO product SELECT * FROM products;

You should really think of improving the scheme you have. 您应该真正考虑改善现有方案。 You have a lot of duplicated information which will cause performance and maintenance hell. 您有很多重复的信息,这会导致性能和维护困难。 The table products should not store information for a given product but rather should only have a foreign key to a product in the second table product. 表产品不应存储给定产品的信息,而应仅在第二个表产品中具有产品的外键。

Try: 尝试:

INSERT INTO product VALUES (product_id, lenght, width, height)
  SELECT products_id, products_lenght, products_width, products_height 
  FROM products
  WHERE products_id=3

You can remove WHERE clause if you want to insert all records of products. 如果要插入产品的所有记录,则可以删除WHERE子句。

Are you just asking for this? 您只是要这个吗?

INSERT INTO
    product (product_id, length, width, height)
SELECT
    products_id
    ,products_length
    ,products_width
    ,products_height
FROM
    products

If you're just trying to migrate data, can you just copy the table? 如果您只是想迁移数据,可以复制表吗? Or rename it and the columns? 还是重命名它和列?

Firstly, i'd suggest you improve your DB schema - your duplicating some information. 首先,我建议您改善数据库架构-复制一些信息。

But to answer you could use: 但要回答,您可以使用:

INSERT INTO product (product_id, length, width, height) 
SELECT products_id ,products_length ,products_width ,products_height FROM products

Another option would be to duplicate the table, rename it and then rename your columns? 另一个选择是复制表,重命名表,然后重命名列?

Refer the documentation: http://dev.mysql.com/doc/refman/5.0/en/insert-select.html 请参考文档: http : //dev.mysql.com/doc/refman/5.0/en/insert-select.html

and Use : 和使用:

INSERT INTO product (product_id, length, width, height) 
SELECT products_id ,products_length ,products_width ,products_height 
FROM products 

Before copying the data, also verify the schema for both tables. 复制数据之前,还要验证两个表的架构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM