• mysql_表_操作


    1、创建表

    # 基本语法:
    create table 表名(
        列名  类型  是否可以为空  默认值  自增  主键,
        列名  类型  是否可以为空
    )ENGINE=InnoDB DEFAULT CHARSET=utf8
    
    not null         # 不可以为空
    default 1        # 默认值为1
    auto_increment   # 自增
    primary key      # 主键
    constraint 外键名 foreign key (从表字段’自己‘) references 主表(主键字段)    # 外键

    2、查看表结构

    desc 表名

    3、删除表

    drop table 表名

    4、清空表

    # 表还存在,表内容清空
    
    delete from 表名
    truncate table 表名

    5、修改表

    # 添加列:
            alter table 表名 add 列名 类型

    # 删除列:
            alter table 表名 drop column 列名

    # 修改列数据类型:
            alter table 表名 modify column 列名 类型; 

    # 修改列数据类型和列名:
        alter table 表名 change 原列名 新列名 类型; 

    # 添加主键:
            alter table 表名 add primary key(列名);
    # 删除主键:
            alter table 表名 drop primary key;
    # 添加外键:
            alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
    # 删除外键:
            alter table 表名 drop foreign key 外键名称
    # 修改默认值:
            ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
    # 删除默认值:
            ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
    # 更改表名
             rename table 原表名 to 新表名;

    #增加表字段,altertable法。
    1>    语法: altertable 表名 add 字段 类型 其他;
    2>    插入列,名为sex。
    mysql> alter table student add sex char(4);
    Query OK, 3 rows affected (0.01 sec)
    Records: 3  Duplicates: 0  Warnings: 0
    
    mysql> select * from student;
    +----+----------+-----+------+------+
    | id | name     | age | dept | sex  |
    +----+----------+-----+------+------+
    |  2 | oldsuo   |   0 | NULL | NULL |
    |  3 | kangknag |   0 | NULL | NULL |
    |  4 | kangkang |   0 | NULL | NULL |
    +----+----------+-----+------+------+
    3 rows in set (0.00 sec)
    3>    插入名为suo列在name后面。
    mysql> alter table student add suo int(4) after name;
    Query OK, 6 rows affected (0.00 sec)
    Records: 6  Duplicates: 0  Warnings: 0
    4>    插入名为qq列在第一。
    mysql> alter table student add qq varchar(15) first;
    Query OK, 6 rows affected (0.00 sec)
    Records: 6  Duplicates: 0  Warnings: 0

    参考:https://www.cnblogs.com/suoning/articles/5769141.html

  • 相关阅读:
    剑指offer---二叉搜索树的第k个结点
    剑指offer---把数组排成最小的数
    剑指offer---连续子数组的最大和
    剑指offer---最小的K个数
    Navicat for MySQL(Ubuntu)过期解决方法
    Ubuntu 无法应用原保存的显示器配置
    ubuntu 18.04 install gitlab-ce
    Flask 使用过程
    python版本 3.7.4rc1 (stable) / 3.8.0b1 (pre-release) / 3.9.0a0 (in development)
    Windows10 and MySQL使用
  • 原文地址:https://www.cnblogs.com/cui0x01/p/8640431.html
Copyright © 2020-2023  润新知