登录
首页 >  数据库 >  MySQL

MySQL学习之聊聊怎么向表中添加新列(字段)

来源:SegmentFault

时间:2023-02-16 15:23:06 233浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习数据库相关编程知识。下面本篇文章就来带大家聊聊《MySQL学习之聊聊怎么向表中添加新列(字段)》,介绍一下MySQL,希望对大家的知识积累有所帮助,助力实战开发!

我们使用

alter table table_name
add [column] column_name column_definition [first|after existing_column];

说明:

  • alter table table_name
    add [column] column_name column_definition [first|after existing_column],
    add [column] column_name column_definition [first|after existing_column],
    ...;

    举例

    创建一个表

    create database test;
    use test;
    
    create table if not exists vendor (
        id int auto_increment primary key,
      name varchar(255)
    );

    添加新列并指定位置

    alter table vendor
    add column phone varchar(15) after name;

    添加新列但不指定新列位置

    alter table vendor
    add column vendor_group int not null;

    插入记录

    insert into vendor(name, phone, vendor_group)
    values('IBM', '(408)-298-2987', 1);
    
    insert into vendor(name, phone, vendor_group)
    values('Microsoft', '(408)-298-2988', 1);

    同时添加两列

    alter table vendor
    add column email varchar(100) not null,
    add column hourly_rate decimal(10, 2) not null;
    注意:email和hourly_rate两列都是not null,但是vendor表已经有数据了,在这种情况下,MySQL将使用这些新列的默认值。

    检查vendor表中的数据

    select id, name, phone, vendor_group, email, hourly_rate
    from vendor;

    查询结果:

    +----+-----------+----------------+--------------+-------+-------------+
    | id | name      | phone          | vendor_group | email | hourly_rate |
    +----+-----------+----------------+--------------+-------+-------------+
    |  1 | IBM       | (408)-298-2987 |            1 |       |        0.00 |
    |  2 | Microsoft | (408)-298-2988 |            1 |       |        0.00 |
    +----+-----------+----------------+--------------+-------+-------------+
    2 rows in set (0.00 sec)
    email列中填充了空值,而不是NULL值,hourly_rate列填充了0.00

    添加表中已存在的列

    MySQL将发生错误

    alter table vendor
    add column vendor_group int not null;

    操作结果:

    ERROR 1060 (42S21): Duplicate column name 'vendor_group'

    检查表中是否已存在列

    对于几列的表,很容易看到哪些列已经存在,如果有一个饮食数百列的大表,那就比较费劲了

    select if(count(*) = 1, 'Exist', 'Not Exist') as result
    from information_schema.columns
    where table_schema = 'test'
        and table_name = 'vendor'
        and column_name = 'phone';

    查询结果:

    +--------+
    | result |
    +--------+
    | Exist  |
    +--------+
    1 row in set (0.00 sec)
    在where子句中,我们传递了三个参数:表模式或数据库,表名和列名。我们使用if函数来返回列是否存在。

    参考

    https://www.begtut.com/mysql/...

    文中关于mysql的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《MySQL学习之聊聊怎么向表中添加新列(字段)》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表