数据库查询语句(DQL)

DQL:
数据库执行DQL语言不会对数据库中的数据发生任何改变,而是让数据库发送查询结果到客户端。python

*执行语句不改变表内容正则表达式

查询表格全部列:select * from 表名;数据库

查询某一列内容:select 列名 from 表名 ;函数

查询指定多列内容:select 列名1 ,列名2,... from 表名;code

where :

使用运算符
=, !=, <, >, <=, >=
between...and: 介于...和...之间
and 且
or 或
in /not in # 在in内的/除了in内的
is /is not # 相似于python中的身份运算符,经常使用于判断null值it

like :

_   :  匹配单个任意字符
% :匹配0-n我的任意字符【n大于等于1】 == 正则表达式的+

as ( 起别名 ):

select 字段 as 别名    	# 将字段名字换成别名 并输出到控制台,不会改变原有表格属性

distinct(去重) :

select distinct  字段 from 表名 ;     # 将字段的数据去重

order by ( 升降序 ) :

# asc 升序  
# desc 降序
select * from 表名 order by 字段 asc/desc ;

聚合函数:

select 聚合函数 from 表名 ;
    count (统计出现的次数) :
select count(*) from 表名 where 条件;
# 统计表格中分数大于80的个数  
select count(*) from 表名 where  score>80 ;

sum (求和): sum(字段)
select sum(age) from student ;
max(最大值) :max(字段)
min(最小值) : mix(字段)
avg (求平均数) : avg(字段)io

group by (分组查询):

# 查询以某个字段为分组,计算分组内的数据,好比每一个组多少个
group by 分组的字段

having: 有...,表示条件,相似于where

where 必须在 group by 前面 由于group by后面的过滤条件是 having
where 后面不能够使用聚合函数, having 后面能够使用聚合函数select

多表联查:

union 去除重复记录(去重)
union all 获取全部的结果 (并集)

前提:列表之间的字段类型,列数必须相同
去重: select * from 表一 union select * from 表二 ;
并集: select * from 表一 union all select * from 表二 ;nio

表链接:

select * from 表一,表二 ;      # 会输出笛卡尔积 即两个集合相乘

解决方法:
select (想要查看的字段,能够用 student.id(表,字段) 写入)from 表名 where 两个表中的相同的参数(去重);方法

内链接 :

inner join on == join on     on至关于where
特色:查询结果必须知足条件,
         on条件后面的两个字段名必须同样,至关于表一和表二都必须拥有这个字段
select 表.字段 from  表一 join 表二  on 表一.字段=表二.字段 ;
等价于
select 表.字段 from  表一 , 表二  on 表一.字段=表二.字段 ;

外链接 :

left join on  左外链接
right join on 右外链接
select 表.字段 from  表一 left join 表二  on 表一.字段=表二.字段 ;

select 表.字段 from  表一 right join 表二  on 表一.字段=表二.字段 ;

SQL书写顺序:select => from => where => group by => having => order by => limit SQL执行顺序:from => where => group by => having => order by => select => limit

相关文章
相关标签/搜索