引言
分享一下,SQL的基础,多多练习!!!
语法
一步步由浅到深,这里用的都是MySQL做的。
基础
连接数据库
- 1
- 1
-h后面是mysqlServer所在地址,-u后面是用户名,-p后面是密码
查看数据库
- 1
- 1
使用数据库
- 1
- 1
查看表
- 1
- 1
查看表结构
- 1
- 1
建表
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
语法 create table 表名称( 字段名 字段名类型 字段描述符,字段名 字段类型 字段描述符);
删除表
- 1
- 1
语法:drop table 表名称;
修改表
添加字段
- 1
- 1
语法:alter table 表明称 add(字段名 类型 描述符);
移除字段
- 1
- 1
语法:alter table 表名 drop colunm 字段名,drop colunm 字段名;
变更字段
- 1
- 1
语法:alter table 表名 change 旧字段名 新字段名 新字段描述符
插入
全字段插入
- 1
- 1
语法:insert into 表名 values(字段1值,字段2值,……),(字段1值,字段2值,……);
个别字段插入
- 1
- 1
查看插如后的结果,如上图所示。
语法:insert inton 表名(字段名) values(值一),(值二);
普通查询
单表全字段查询
- 1
- 1
语法:select * from 表名;
单表个别字段查询
- 1
- 1
语法:select 字段一,字段二 from 表名;
多表查询
- 1
- 1
语法:select 表一字段,表二字段,表三字段,…… from 表一,表二,表三,……;
条件查询
单表条件查询
- 1
- 1
语法:select 字段1,字段2 from 表名 where 条件;
多表条件查询
- 1
- 1
语法:select 表一字段,表二字段 from 表一,表二 where 条件;
嵌套查询
- 1
- 1
语法:select 字段一,字段二…… from 表名 where 条件(查询);
并查询
- 1
- 1
交查询
- 1
- 1
删除
- 1
- 1
语法:delete from 表名 where 条件;
更新
- 1
- 1
语法:update 表名 set 更改的字段名=值 where 条件;
常用函数
求和
- 1
- 1
注:sum(字段) 对字符串和时间无效
求平均值
- 1
- 1
注:avg(字段)对字符串和时间无效
计数
- 1
- 1
注:count(字段名)不包含NULL;
求最大值
- 1
- 1
注:max(colunm)返回字母序最大的,返回数值最大的
求最小值
- 1
- 1
注:min(colunm)返回字母序最小值,返回数值最小值
常用的修饰符
distinct 字段中值唯一
- 1
- 1
limit查询结果数限制
- 1
- 1
order by 排序
- 1
- 1
注:默认是升序
desc 降序
- 1
- 1
asc 升序
- 1
- 1
group by 分组
- 1
- 1
索引
创建普通索引
- 1
- 1
语法:create index 索引名称 on 表名 (字段一,字段二,……);
创建唯一索引
- 1
- 1
语法:create unique index 索引名 on 表名 (字段一,字段二,……);
ps:unique index 要求列中数据唯一,不能出现重复。
移除索引
- 1
- 1
语法: drop index 索引名 on 表名;