如何在SQL中从旧表迁移数据到新表,并设置一些默认值?

huangapple go评论106阅读模式
英文:

How to migrate data to new table with some default value from old table in SQL

问题

我有一个名为User的表,其中包含字段username和password。我想创建一个名为tracking_user的表,该表包含以下字段:username、password、custom和time。请问我该如何创建SQL脚本来创建tracking_user表,其中的username和password字段来自user表,custom字段的默认值为0,而time字段的值应该是运行脚本时的当前时间。非常感谢!

英文:

I have table User with field username, password. I want to create tracking_user table with these field: username, password, custom, time. How can I create SQL script to create tracking_user with username, password from user table and custom have default value 0 and time is now when running script. Thank you so much!

答案1

得分: 2

  1. 克隆您的用户表结构:
CREATE TABLE tracking_user LIKE user;
  1. 向新表添加额外列:
ALTER TABLE tracking_user ADD custom INT(11) NOT NULL DEFAULT '0' AFTER password, ADD time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER custom;
  1. 将您的用户表数据克隆到新表:
INSERT INTO tracking_user (username, password) SELECT username, password FROM user;
英文:

For that you need to create 3 different SQL queries like below.

1) Clone your user table structure

CREATE TABLE tracking_user LIKE user;

2) Add additional column to new table

ALTER TABLE tracking_user ADD custom INT(11) NOT NULL DEFAULT '0' AFTER password, ADD time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER custom;

3) Clone your user table data to new table

INSERT INTO tracking_user (username, password) SELECT username, password FROM user;

huangapple
  • 本文由 发表于 2023年6月22日 12:40:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定