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;

相关推荐
WL_Aurora8 分钟前
MySQL 5 卸载到 MySQL 8 安装完整指南(不踩坑版)
数据库·mysql
灰阳阳10 分钟前
MySQL的基本架构
数据库·mysql·架构
@小柯555m29 分钟前
MySql(高级操作符--Where in 和Not in)
数据库·sql·mysql
许彰午30 分钟前
CacheSQL(一):手写数据库的工程化重生
java·数据库·缓存
MmeD UCIZ31 分钟前
MySQL单表存多大的数据量比较合适
数据库·mysql
SarL EMEN1 小时前
mysql之联合索引
数据库·mysql
l1t1 小时前
DeepSeek总结的DuckDB anofox-forecast季节调整时间序列预测插件功能
开发语言·数据库
meta INGU1 小时前
mysql数据被误删的恢复方案
数据库·mysql
27669582921 小时前
acw_sc__v2
数据库·acw_sc__v2·acw_sc__v2逆向·acw_sc__v2算法分析·acw_sc__v2分析·acw_sc__v2还原·acw_sc__v2-ck
Empty-Filled1 小时前
Claude Gateway 排查教程
网络·数据库·人工智能