(四)SQL | 数据定义语言DDL


        本篇介绍SQL的数据库定义语言DDL,主要有数据库的增删改用、表的增删改查,并且配套有MySQL实操练习。


01 数据库的增删查用

1.1 基本语法 

-- 查询数据库
SHOW DATABASES;  -- 查询所有数据库
SELECT DATABASE();  -- 查询当前使用的数据库(要先使用数据库,再查询)

-- 增加数据库
CREATE DATABASE database_name;
CREATE DATABASE [IF NOT EXISTS] database_name [DEFAULT CHERSET character_set][COLLATE sort_rule];  -- if not exists 不容易报错

-- 删除数据库
DROP DATABASE database_name;
DROP DATABASE [IF EXISTS] database_name;

-- 使用数据库
USE database_name;

1.2 MySQL实操

  • 全局搜索MySQL Workbench 8.0 CE,打开。

  • 新建一个连接MySQL Class,打开。

  • 在界面中进行操作。运行代码:选中要运行的代码,Ctrl+Shift+Enter即可(单行Crtl+Enter即可)
  1.  使用

  2. 查询

  3. 增加

  4. 删除


02 表的增删改查

2.1 基本语法  

2.1.1 表的查询 

-- 查询表(当前数据库的所有表)
show tables;

-- 查询表结构
desc table_name;

-- 查询表的建表语句
show create table table_name;

2.1.2 表的创建

create table [if not exists] 表名 (
    列名1 列1类型 [comment 列1注释]  -- comment声明
    , 列名2 列2类型 [comment 列2注释]
    , ...
) [comment 表注释];

2.1.3 表的数据类型

  • 数值类型
  • 字符串类型
  • 日期时间类型
SQL 数据类型

2.1.4 表的修改

-- 修改表名
ALTER TABLE 表名 RENAME TO 新表名;

-- 添加列
ALTER TABLE 表名 ADD 列名 类型 [COMMENT 注释][约束];

-- 修改列
ALTER TABLE 表名 MODIFY 列名 新类型;  -- 修改数据类型
ALTER TABLE 表名 CHANGE 旧列名 新列名 类型 [COMMENT 注释][约束];  -- 修改字段名和字段类型

-- 删除列
ALTER TABLE 表名 DROP 列名;

2.1.5 表的删除

DROP TABLE [IF EXISTS] 表名;  -- 删除表
TRUNCATE TABLE 表名;  -- 删除表,再重新创建该表

 

2.2 MySQL实操

2.2.1 表的查询

use world;
show tables;
desc city;
show create table city;
show tables;

desc city;

show create table city;

2.2.2 表的创建

如:创建学生表student(MySQL)

学生表:student
表结构备注
编号纯数字
学号字符串类型,长度不超过8
姓名字符串类型,长度不超过10
性别男/女,1个汉字
年龄大于0的整数
身份证号18位,身份证中有X
出生日期年月日
班级字符串类型,长度不超过5
create database if not exists test;
use test;
drop table if exists student;

-- 创建表
create table student (
	id int comment "编号"
    , s_num varchar(8) comment "学号"
    , s_name varchar(10) comment "姓名"
    , gender char(1) comment "性别"
    , age tinyint unsigned comment "年龄"
    , id_card char(18) comment "身份证号"
    , birth_date date comment "出生日期"
    , class varchar(5) comment "班级"
) comment "学生表";

desc student;  -- 查询表结构
show create table student;  -- 查询建表语句
desc student;

show create table student;

2.2.3 表的修改

-- 增加列
alter table student add eng_name varchar(10) comment "英文名";  
desc student;

-- 修改列
alter table student modify s_num varchar(12);  -- 将s_num列修改为最长不超过12的字符串类型 
alter table student change s_num s_number varchar(12) comment "学号";  -- 将s_num改为s_number,字符串类型,长度不超过8
desc student;

-- 删除列 
alter table student drop eng_name;

-- 修改表名 
alter table student rename to stu_tb;
show tables;
增加列-desc student;

修改列-desc student;

删除列-desc student;

修改表名-show tables;

2.2.4 表的删除

truncate table stu_tb;  -- 删除表,再建一个相同结构的表
show tables;
desc stu_tb;

drop table if exists stu_tb;  -- 删除表
show tables; 
truncate-删除表,再建一个相同结构的表

drop-删除表

不总结=白学


 THE END


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值