1、SQL查询
1、总结
3、select 聚合函数 from 表名
1、where 条件
2、group by ...
4、having ...
5、order by ...
6、limit ...
2、group by :给查询的结果进行分组
注意 : 查询字段和group by后字段不一致,则必须对该查询字段进行聚合处理(聚合函数)
3、having语句 :对分组聚合后的结果进一步筛选
注意 : having语句通常和group by语句联合使用,having语句弥补了where关键字不能与聚合函数使用的不足,where只能操作表中实际存在字段
4、distinct :不显示字段的重复值
5、查询表记录时做数学运算
+ - * / %
2、嵌套查询(子查询)
定义 :把内层的查询结果作为外层的查询条件
select .. from 表名 where 字段名 运算符 (查询);
3、多表查询
1、笛卡尔积 :select ... from 表1,表2; 不加where
2、多表查询 :加 where 条件
4、连接查询
1、内连接(inner join :只显示满足匹配条件的结果)
select ... from 表1 inner join 表2 on 条件;
2、左外连接(left join:以左表为主显示查询结果)
select ... from 表1 left join 表2 on 条件;
3、右外连接(right join:以右表为主显示查询结果)
5、约束
1、非空约束(NOT NULL)
不允许该字段值有NULL记录
create ...(name varchar(20) NOT NULL,
2、默认约束(DEFAULT 值)
插入记录时,不给该字段赋值,则使用默认值
create ...(sex enum("M","F","S") not null default "S"
6、索引
1、定义 :对数据表的一列或者多列的值进行排序的一种结构(BTree)
2、优点 :加快数据检索速度
3、缺点
1、占用物理存储空间
2、当对表中数据更新时,索引需要动态维护,降低数据维护速度
4、索引示例
查看变量状态 :show variables like "%pro%";
1、开启运行时间监测
mysql> set profiling=1;
2、执行1条查询语句(无索引)
select name from t1 where name="lucy99999";
3、在name字段创建索引
create index name on t1(name);
4、再执行1条查询语句(有索引)
select name from t1 where name="lucy100000";
5、查看执行时间
mysql> show profiles;
6、关闭运行时间监测
mysql> set profiling=0;
7、索引分类
1、普通索引(index)、唯一索引(unique)使用规则
1、可创建多个字段
2、普通索引无约束,唯一索引要求字段值不允许重复,但可为NULL
3、KEY标志 :普通(MUL) 唯一(UNI)
4、经常用查询的字段、where后、order by排序字段创建索引
2、创建
create table t1(
... ...,
index(字段名),
index(字段名),
unique(字段名),
unique(字段名)
)charset=utf8;
create [unique] index 索引名 on 表名(字段名);
3、查看
1、desc 表名; --> KEY标志
2、show index from 表名\G;
4、删除
drop index 索引名 on 表名;
安装pymysql
在线 :
sudo pip3 install pymysql
离线 :
1、下载 xxx.tar.gz
2、进入解压后的目录,找 setup.py
3、sudo python3 setup.py install
总结 :
1、SQL查询
1、聚合函数
avg(...) sum(...) max(...) min(...)
count(字段名) ## 空值NULL不会被统计
2、group by :对查询结果进行分组
先分组再聚合
如果select后的字段名和group by后字段不一致,则必须对该字段进行聚合处理
3、having语句 :对查询结果进行进一步筛选
where只能操作表中实际存在的字段(desc 表名;)
4、distinct :不显示字段的重复值
select distinct 字段1,字段2 from 表名;
5、查询时做数学运算
select 字段1+100 as n1,字段2*50 as n2 from 表名
2、嵌套查询(子查询)
把内层的查询结果作为外层的查询条件
3、多表查询
1、笛卡尔积 :不加where条件
2、多表查询 :加where条件,只显示匹配到的
4、连接查询
1、内连接 :只显示匹配到的记录
2、外连接
1、左连接 :以左表为主显示查询结果
2、右连接 :以右表为主显示查询结果
3、select 表名.字段名 from 表1
inner/left/right join 表2 on 条件
inner/left/right join 表3 on 条件;
5、约束
1、非空约束 :NOT NULL
2、默认约束 :DEFAULT 值
## name varchar(20) NOT NULL DEFAULT "匿名"
6、索引(BTree)
1、优点 :加快数据的查询速度
2、缺点
1、占用物理存储空间
2、索引需动态维护,占用系统资源
3、SQL命令运行时间监测
show variables like "%pro%";
1、开启 :mysql> set profiling=1;
2、查看 :mysql> show profiles;
3、关闭 :mysql> set profiling=0;
7、普通(MUL)、唯一(UNI,字段值不重复,但可为NULL)
1、创建表时创建
create table 表名(
id int,
name varchar(20),
phnum bigint,
index(name),
unique(phnum)
)charset=utf8;
2、已有表中创建
create index 索引名 on 表名(字段名);
create unique index 索引名 on 表名(字段名);
3、查看
desc 表名; --> KEY标志
show index from 表名\G;
4、删除
drop index 索引名 on 表名;