快速将列的副本添加到 MySQL 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2185458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:10:36  来源:igfitidea点击:

Quickly add a copy of a column to a MySQL table

sqlmysql

提问by Robbie

I need a fast way duplicate a DATETIME column in a table and give it a new name.

我需要一种快速的方法来复制表中的 DATETIME 列并为其指定一个新名称。

I have a column named myDate in my table called myResults, I need a query to make a new column in the table called newDate which has the exact same data as the myDate column.

我在名为 myResults 的表中有一个名为 myDate 的列,我需要一个查询来在名为 newDate 的表中创建一个新列,该列与 myDate 列具有完全相同的数据。

Is there a faster way to do this than by doing the obvious 2 step approach of make a new column, and then copying all the data (it's a large table and I'm looking for the fastest approach)?

有没有比通过明显的两步方法创建一个新列,然后复制所有数据(它是一个大表,我正在寻找最快的方法)更快的方法来做到这一点?

Obvious solution:

明显的解决方案:

 ALTER TABLE `myResults` ADD `newDate` DATETIME;  
 UPDATE `myResults` SET `newDate` = `myDate`;

采纳答案by Daniel Vassallo

The obvious solution is the only solution, unfortunately.

不幸的是,显而易见的解决方案是唯一的解决方案。

However note that in general you shouldn't be copying a column in relational databases.

但是请注意,通常您不应复制关系数据库中的列。

回答by Basharat Ali

UPDATE `table_name` SET `new_column` = `existing_column` WHERE `id`=`id`

回答by Evan Carroll

Why would your workload ever demand a new datetime column, that duplicates another columns data? This sounds like horrable practice? How about telling us what you're trying to achieve? You can pull a second column with the same data in a few different ways, without actually duplicating the data:

为什么您的工作负载需要一个新的日期时间列来复制另一列数据?这听起来像可怕的做法?告诉我们你想要达到的目标如何?您可以通过几种不同的方式提取具有相同数据的第二列,而无需实际复制数据:

SELECT date1 AS date_old, date1 AS date_new FROM table;

-or-, you can create a view

-或者-,你可以创建一个视图

CREATE VIEW virtual_table AS
    SELECT date1 AS date_old, date1 AS date_new FROM table
;
SELECT * FROM virtual_table;

回答by Matt

If you just need a default in there, you can either choose what the default is statically or use a function call.

如果您只需要那里的默认值,您可以静态选择默认值或使用函数调用。

ALTER TABLE `myResults` ADD `newDate` DATETIME DEFAULT '2010-01-01';

or

或者

ALTER TABLE `myResults` ADD `newDate` DATETIME DEFAULT current_timestamp;