1.sql 通用语法
- 语句可以单行或多行,以分号结尾
- 语句可以使用扣个/缩进来增强可读性
- 语句不区分大小写,关键词用大写
- 注释:
- 单行注释–
- 多行注释 /* 注释内容 */
2.sql分类
- DDL 数据库定义语言,定义数据库对象
- DML 数据库操作语言,对数据库表中的数据进行增删改
- DQL 数据库查询语言,用来查询数据库中表的记录
- DCL 数据库控制语言,用来创建数据库用户,控制用户权限
3.DDL
数据库操作
- 查询所有数据库
show databases;
- 查询当前数据库
select database();
- 创建
create database [if not exists] 数据库名称 [utf8mb4 字符集] [collate 排序]
create database itcast;
create database if not exists itcast2;
create database itcast3 default charset uf8mb4;
- 删除
drop database [if not exists] 数据库名称 ;
drop database itcast;
- 使用
use itcast;
表操作-查询
- 查询所有表
show tables;
- 查询表结构
desc 表名;
- 查询指定表的建表语句
show create table 表名;
表操作-创建
create table 表名(
字段1 字段1类型 [comment 字段1注释],
字段2 字段2类型 [comment 字段2注释],
) [comment 表名称]
create table ta_user(
id int comment '编号',
name varchar(50) comment '姓名',
age int comment '年龄',
gender varchar(1) comment '性别'
) comment '用户表';
表操作-数据类型
分类 | 类型 | 大小 | 有符号(signed)范围 | 无符号(unsigned)范围 | 描述 |
---|---|---|---|---|---|
数值类型 | tinyint | 1 bytes | (-128, 127) | (0, 255) | 小整数值 |
数值类型 | smallint | 2 bytes | (-32768, 32767) | (0, 65535) | 大整数值 |
数值类型 | mediumint | 3 bytes | (-8388608, 838867) | (0, 16777215) | 大整数值 |
数值类型 | int或integer | 4 bytes | (, ) | (0, ) | 大整数值 |
数值类型 | bigint | 8 bytes | (, ) | (0, ) | 大整数值 |
数值类型 | float | 4 bytes | (, ) | (0, ) | 单精度浮点数值 |
数值类型 | double | 8 bytes | (, ) | (0, ) | 双精度浮点数值 |
数值类型 | decimal | (, ) | (0, ) | 小数值(精确定点数) | |
字符串类型 | char | 0-255 b | - | - | 定长字符串 |
字符串类型 | varchar | 0-65535 b | - | - | 变长字符串 |
字符串类型 | text | 0-65535 b | - | - | 长文本数据 |
…
表操作-修改
- 添加字段
alter table 表名 add 字段名 类型(长度) [comment 注释] [约束]
alter table ta_user add nickname varchar(20) comment '昵称';
- 修改数据类型
alter table 表名 modify 字段名 新类型(长度)
alter table ta_user modify nickname char(20);
- 修改字段名和数据类型
alter table 表名 change 旧字段名 新字段名 新类型(长度) [comment 注释] [约束]
alter table ta_user change nickname username varchar(30) comment '昵称';
- 修改表名
alter table 表名 rename to 表名;
alter table ta_user rename to emp;
表操作-删除
- 删除字段
alter table 表名 drop 字段名;
alter table ta_user drop username;
- 删除表
drop table [if not exists] 表名;
drop table ta_user;
- 删除指定表,并创建该表
truncate table [if not exists] 表名;
truncate table ta_user;
删除表时,表中数据也会删除