Mysql——DQL(查询语句语法、格式、举例源码)

  • 基本语法
  • 一.基础查询
  • 1.查询多列
  • 2.查询全表
  • 3.去除重复记录
  • 4.修改表头
  • 二.条件查询
  • 1.基础语法
  • 2.多条件查询
  • 2.1比较条件
  • 2.2确定范围的关键字
  • 2.3确定集合的关键字
  • 2.4空值
  • 2.5多重运算
  • 模糊查询
  • 三.排序查询
  • 1.升序降序单字段排列
  • 2.多字段排序
  • 四.聚合函数
  • 五.分组查询
  • 1.语法和注意事项
  • 2.where和having的区别
  • 3.举例
  • 六.分页查询
  • 1.关键字和语法
  • 2.举例


基本语法

mysql 查看表字段的排序编码 mysql查询排序语句_数据库开发

一.基础查询

1.查询多列

语法

select 列名1,列名2……列名n from 表名;

2.查询全表

语法

select * from 表名

3.去除重复记录

语法
加一个distinct关键字

select distinct 列名1,列名2……列名n from 表名;

4.修改表头

select 列名1 as 新列名1,列名2 as 新列名2…… from 表名;
其中as关键字可以不写。

二.条件查询

1.基础语法

语法

select 列名 from 表名 where 条件;

2.多条件查询

2.1比较条件

包括:=, >, <, >=, <=, !=, <>(不等于), !>, !<;
下面完成几个需求实现查询:
年龄在10以上20以下的
语法

select 列名 from 表名 where age<20 && age >10;
或者&&用and,表示并且
or和||表示或者

2.2确定范围的关键字

between and
not between and

-- 查找id在20到30之间的同学信息
select * from student where id between 20 and 30;

2.3确定集合的关键字

in ,not in

select * from 表名 where 列名 in (value)
-- 	查询住在北京和上海的同学
select * from student where adr in ('北京','上海');

2.4空值

is null ,not is null

-- 查询成绩为空的同学信息
select * from 表名 where 列名 is null
select * from student where score is null;

2.5多重运算

select * from 表名 where 列名 id < 10 and adr in 'China' or id >5 and adr in 'HongKong'

模糊查询

mysql 查看表字段的排序编码 mysql查询排序语句_mysql_02

#查询第二个字是花的
select * from stu where name like '_花%'
#查询有圣的
select * from stu where name like '%圣%'

三.排序查询

语法

mysql 查看表字段的排序编码 mysql查询排序语句_数据库架构_03

1.升序降序单字段排列

select * from 表名 order by 排序字段名[排序方式]
asc升序
desc降序
如果不指定
默认asc

2.多字段排序

语法同上,但是在第一个字段排完才排第二个

四.聚合函数

语法

mysql 查看表字段的排序编码 mysql查询排序语句_sql_04


注意null不参与任何计算

select count(*) from stu
统计表中的学生数量
select max(math) from stu
求最大分数的同学
select avg(math) from stu
求数学的平均分

五.分组查询

1.语法和注意事项

mysql 查看表字段的排序编码 mysql查询排序语句_数据库架构_05

2.where和having的区别

where是在分组前的判断,having是在分组后的判断
where不能对聚合函数进行判断,having可以
执行顺序where>聚合函数>having

3.举例

查询男女同学各自的平均分,以及人数,要求:且小于60分不参与分组,每组不少于2人
select  sex,avg(math),count(*) from stu where score>60
group by sex having count(*) > 2;

六.分页查询

mysql 查看表字段的排序编码 mysql查询排序语句_mysql 查看表字段的排序编码_06

1.关键字和语法

使用关键字limit

select 列名 from 表名 limit 起始索引,查询条数

2.举例

每页显示3条数据,查询第三页
起始索引=(查询页数-1)*每页的条目数
select * from stu limit 6,3;