如何将 MySQL 中的列默认值分配给另一列的值?

发布于 2024-07-15 11:09:37 字数 68 浏览 5 评论 0原文

我想向 MySQL 数据库中的表添加一个新列,该新列应该获取同一表中另一列的值。 这可能吗? 如果是这样,你会怎么做?

I want to add a new column to a table in MySQL database that should get the value of another column in the same table. Is this possible? If so, how do you do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

时光倒影 2024-07-22 11:09:37

从 MySQL 5.0.2 开始,您可以编写链接到 TRIGGER 可以在每次插入行时检查新列,如果没有为新列提供值,则自动将另一列的值复制到新列中。

Starting with MySQL 5.0.2 you can write a stored procedure linked to a TRIGGER which can examine the new column each time a row is inserted, and automatically copy the other column's value into the new column if no value was supplied for the new column.

紫南 2024-07-22 11:09:37

您可以使用以下两个命令来完成您的工作。

  1. 此命令将用于在表中添加新列。 记住要复制的数据类型,以便在新列中使用这些数据类型。

    ALTER TABLE table_name ADD new_column_name VARCHAR(60); 
      

2:此命令将数据从旧列名复制到新列名。

   UPDATE table_name SET new_column_name = old_column_name;

然后如果你想删除上一列,那么你可以使用以下命令

   ALTER TABLE table_name DROP COLUMN old_column_name;

You Can use this following two command to do your work.

  1. This command will be used to add new column in you table. Remember data type from where you want to copy to use those data type in new Column.

    ALTER TABLE table_name ADD new_column_name VARCHAR(60);
    

2: This command to copy data from old column name to new column name.

   UPDATE table_name SET new_column_name = old_column_name;

Then if you want to delete previous column, Then you can use following command

   ALTER TABLE table_name DROP COLUMN old_column_name;
木槿暧夏七纪年 2024-07-22 11:09:37

截至 20101212,mysql 不支持默认 2 个时间戳列,这意味着您无法在同一个表上执行“创建”和“更新”操作。

如果这就是您想要做的,那么带有存储过程的触发器就是正确的选择。

As of 20101212 mysql does not support defaulting 2 timestamp columns, which means you can't do a 'created' and 'updated' on the same table.

If this is what you were trying to do, then the trigger with the stored proc is the way to go.

‖放下 2024-07-22 11:09:37

创建一个视图,您可以选择同一列两次并给它不同的名称,然后应用程序可以使用视图而不是直接使用表。

create a view, and you can select the same column twice and give it different name, then the application can use the view instead use the table directly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文