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;

相关推荐
2401_831824965 分钟前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
2401_8579182915 分钟前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
IvorySQL33 分钟前
PostgreSQL 19 重磅新语法终于补齐这个缺口
数据库·postgresql·开源
IvorySQL41 分钟前
PostgreSQL 技术日报 (3月23日)|使用 rdtsc 减少 EXPLAIN ANALYZE 的计时开销
数据库·postgresql·开源
yhole1 小时前
SQL中的REGEXP正则表达式使用指南
数据库·sql·正则表达式
IvorySQL1 小时前
PostgreSQL 技术日报 (3月21日)|这些机制,可能并非 “ 理所当然 ”
数据库·postgresql·开源
m0_518019481 小时前
使用Seaborn绘制统计图形:更美更简单
jvm·数据库·python
卓怡学长1 小时前
m280本科生导师指导平台
java·数据库·spring·tomcat·maven·intellij-idea
大尚来也1 小时前
Serverless架构深度解析:适用场景、核心局限与破局之道
数据库
Wave8451 小时前
非阻塞按键(单击,双击,长按)
数据库