MySQL中的DDL(一)

关于数据库,就需要先了解数据库、数据库管理系统和SQL。

  • 数据库是一个有组织地存储数据的仓库
  • 数据库管理系统是操纵和管理数据库的大型软件
  • SQL是操作关系型数据库的编程语言

而以上三者之间的关系就是SQL语言通过操作数据库管理系统来操作数据库。

SQL语言又分为,DDL、DML、DQL、DCL。

  • DDL:数据库定义语言,定义数据库对象(数据库,表,字段)
  • DML:数据库操作语言,对数据库表中的数据进行增删改
  • DQL:数据库查询语言,查询数据库中表的记录
  • DCL:数据库控制语言,创建数据库用户、控制数据库的访问权限

DDL-数据库操作

  • 查询所有数据库(即查询当前有哪些数据库)

  • show databases;

  • 查询当前数据库(即查询当前处于哪一个数据库中)

  • select database();

  • 创建数据库([ ] 中的数据可写可不写)

  • create dabase [if not exists] 数据库名 [default charset 字符集] [collate 排序规则];

    例:create dabase if not exists test default utf8mb4;

  • 删除数据库

  • drop database [if exists] 数据库名;

    例:drop datase if exists test;

  • 使用数据库(切换数据库)

  • use 数据库名;

DDL-表操作-查询

  • 查询当前数据库所有表(即查询当前数据库中所有的表)

  • show tables;

  • 查询表结构 (即查询当前表中有哪些字段)

  • desc 表名;

    例:desc student;

  • 查询指定表的建表语句

  • show create table 表名;

    例:show create table student;

DDL-表操作-创建

  • create table 表名 (
    字段1 字段1类型 [ comment 字段1注释 ];
    字段2 字段2类型 [ comment 字段2注释 ];
    字段3 字段3类型 [ comment 字段3注释 ];
    字段4 字段4类型 [ comment 字段4注释 ]
    ) [comment 表注释 ];

    例:create table student (
    id int comment '编号',
    name varchar(50) comment '年龄',
    age int comment '年龄',
    gender varchar(1) comment '性别'
    ) comment '学生表';

DDL-表操作-修改

  • 添加字段

  • alter table 表名 add 字段名 类型(长度) [comment 注释] [约束];

    例:为student表增加一个新的字段"姓名"为name,类型为varchar(20)
    alter table student add name varchar(20) comment '姓名';

  • 修改数据类型(即修改指定字段的数据类型)

  • alter table 表名 modify 字段名 新数据类型(长度);

  • 修改字段名和字段类型

  • alter table 表名 change 旧字段名 新字段名 类型(长度) [comment 注释] [约束];

    例:将student表中的name字段改为username,类型为varchar(30)
    alter table studeng change name username varchar(30) comment '用户名';

  • 删除字段(即删除指定表中的指定字段)

  • alter table 表名 drop 字段名;

    例:将student表中的username 删除
    alter table student drop username;

  • 修改表名

  • alter table 表名 rename to 新表名;

    将student表的表明修改为students;
    alter table student rename to students;

  • 删除表

  • drop table [ if exists ] 表名;

    例:drop table students;

  • 删除指定表,并重新创建改表

  • truncate table 表名

    truncate table students;

相关推荐
倔强的石头_5 小时前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
jiayou641 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
于眠牧北1 天前
MySQL的锁类型,表锁,行锁,MVCC中所使用的临键锁
mysql
李广坤2 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
Turnip12023 天前
深度解析:为什么简单的数据库"写操作"会在 MySQL 中卡住?
后端·mysql
爱可生开源社区3 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1774 天前
《从零搭建NestJS项目》
数据库·typescript
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏4 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐4 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端