SQL基础语法复习

1. DML 数据操作指令

select 查

select 列 from 表  #取某列
select * from 表 #取全部

update 改

update 表 set 列=新值 where 列=某值  #更新列中某个值
update 表 set 列1=新值1, 列2=新值2 where 列=某值 #更新某一行中若干列

delete 删

delete from 表 where 列=值  #删除某行
delete from 表 #删除所有行(不删除表)
delete * from 表  #同上

insert into 增

insert into 表 values (值1,值2,...)  #插入数据
insert into 表(列1,列2,...) values (值1,值2,...) #指定要插入的列

distinct 去重

select distinct 列 from 表

where 条件筛选

select 列 from 表 where 列 运算符 值
## 多条件
select 列 from 表 where 列 运算符 值 and 列运算符 值
select 列 from 表 where 列 运算符 值 or 列运算符 值

order by 指定列结果排序

select 列1,列2 from 表 order by 列1  #默认升序asc
select 列1,列2 from 表 order by 列1  desc #降序
select 列1,列2,列3 from 表 order by 列1 asc, 列3 desc #先按1列升序,再按3列降序

编写和执行顺序

# 编写顺序
select...from...where...group by....having...order by

# 执行顺序
from...where...group by...having ...select...order by

2. DDL 数据定义语言

数据库相关操作

以下[name]表示数据库名称。

show databases # 查看数据库列表
create database [name]  # 创建新数据库
show create databse [name]  # 查看数据库详细信息
alter database [name] charset=编码格式 #修改数据库编码格式
drop database [name] #删除数据库

数据表相关操作

以下[name]表示表格名称。

show tables #查看当前数据库下所有数据表
#创建新表,[]中内容可省略
create table 表名称
(
	列名称1 数据类型[(最大位数) 约束], #文本、数字和日期/时间类型
	列名称2 数据类型[(最大位数) 约束],
	列名称3 数据类型[(最大位数) 约束],
	...    
) engine=引擎名称, charset=编码类型;

show create table [name] #查看表的详细信息
desc [name] #查看表的结构信息

alter table [name] add 列名 数据类型 #表中添加列
alter table [name] drop column 列名 #删除表中列
alter table [name] alter column 列名 数据类型 #修改表中列的数据类型

drop table [name] #删除表
truncate table [name] #删除表内容,但不删除表本身

create index 索引名 on [name]  (列1, 列2, ....) #在表中创建一个简单索引(允许重复),列名规定要索引的列,列名后加desc表降序索引
create unique 索引名 on [name] (列1, 列2, ....) #在表中创建一个唯一索引
alter table [name] drop index 索引名 #删除索引

Ref: SQL基本语法

原文地址:https://www.cnblogs.com/jessepeng/p/13423178.html