简体   繁体   English

从现有表的选定列中以相同的结构在Mysql中创建表

[英]Create a table in Mysql from selected columns of exisiting table and with same structure

I am a newbie and i am using mysql . 我是新手,正在使用mysql I want to create a table product from an existing table customer but i want only the selected columns of customer table to be created in new table and that too with the same structure. 我想从现有的表客户创建表产品 ,但我只希望在新表中创建客户表的选定列,并且也要使用相同的结构。 Eg In customer table there is a column with name DATE which has default as CURRENT_TIMESTAMP and ON UPDATE CURRENT TIMESTAMP . 例如,在客户表中,有一列名为DATE的列,其默认值为CURRENT_TIMESTAMPON UPDATE CURRENT TIMESTAMP SO i want that this structure is also created in the new table. 因此,我希望在新表中也创建此结构。

I looked other answers but they do not copy the structure. 我看了其他答案,但它们没有复制结构。 Please help me 请帮我

Here is what you can do 这是你可以做的

  1. use CREATE TABLE new_table LIKE old_table syntax to create a new table with the same structure 使用CREATE TABLE new_table LIKE old_table语法创建具有相同结构的新表
  2. use ALTER TABLE new_table DROP COLUMN unnecessary_column syntax to drop unnecessary columns in the new table 使用ALTER TABLE new_table DROP COLUMN unnecessary_column语法删除新表中不必要的列
  3. use INSERT INTO new_table ... SELECT ... FROM old_table syntax to copy data 使用INSERT INTO new_table ... SELECT ... FROM old_table语法复制数据

Let's say your customer table looks like 假设您的customer桌看起来像

CREATE TABLE customer
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
  name VARCHAR(5), 
  created DATETIME, 
  modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  other_column INT
);

And you want to create a new table customer_new but without other_column 并且您想创建一个新表customer_new但没有other_column

CREATE TABLE customer_new LIKE customer;
ALTER TABLE customer_new DROP COLUMN other_column;
INSERT INTO customer_new (id, name, created, modified)
SELECT id, name, created, modified
  FROM customer;

Here is SQLFiddle demo 这是SQLFiddle演示

USE THIS 用这个

CREATE TABLE NEW-TAB SELECT NAME,DATE FROM OLD-TAB;

Please change COLUMN/TABLE names as per your requirements 请根据您的要求更改COLUMN / TABLE名称

Try this : 尝试这个 :

create table product(DATE CURRENT_TIMESTAMP,ON UPDATE CURRENT TIMESTAMP );

INSERT INTO product (DATE,ON) SELECT DATE,ON FROM customer ;

OR 要么

CREATE TABLE product  (DATE CURRENT_TIMESTAMP,ON UPDATE CURRENT TIMESTAMP )
       SELECT DATE,ON  FROM customer;  

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

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