Mysql高级语句(进阶查询语句、MySQL数据库函数、连接查询
一、mysql查询语句
先建立lilade数据库,在建立nba表和cba表,用于测试
create database lilade;
create table lilade.nba (id int,name char(4), age int, sex char(2), hobby varchar(20));
create table lilade.cba (id int,name char(4), age int, sex char(2), hobby varchar(20));
1.1、 select ----显示表格中一个或数个字段的所有数据记录
语法
select "字段" from "表名";
例子
select * from nba;
select name from nba;
1.2、 distinct ----不显示重复的数据记录
语法
select distinct "字段" from "表名"
#例子
select distinct name from nba;
1.3、where ----有条件查询
where是对源语句进行条件查询。
语法
select "字段" from "表名" where "条件";
#例子
select store_name from laozi where sales > 1000;
1.4、 and or ----且 或
语法
select "字段" from "表名" where "条件1" {
[and|or] "条件2"}+ ;
#例子
select store_name from laozi where sales > 1000 or (sales < 500 and sales > 200);
1.5 、in----显示已知的值的数据记录
语法
select "字段" from "表名" where "字段" in ('值1', '值2', ...);
#例子
select * from laozi where store_name in ('los angeles', 'houston');
1.6、between----显示两个值范围内的数据记录
语法:select "字段" from "表名" where "字段" between '值1' and '值2';
#例子
select * from laozi where date between '2020-12-06' and '2020-12-10';
1.7、 通配符
#语法:
select 字段名 from 表名 where 字段 like 模式
通配符 | 含义 |
---|---|
% | 表示零个,一个或者多个字符 |
_ | 下划线表示单个字符 |
A_Z | 所有以A开头 Z 结尾的字符串 ‘ABZ’ ‘ACZ’ 'ACCCCZ’不在范围内 下划线只表示一个字符 AZ 包含a空格z |
ABC% | 所有以ABC开头的字符串 ABCD ABCABC |
%CBA | 所有以CBA结尾的字符串 WCBA CBACBA |
%AN% | 所有包含AN的字符串 los angeles |
_AN% | 所有 第二个字母为 A 第三个字母 为N 的字符串 |
1.8 、like ----模糊匹配
- 一般和通配符配合使用。
- 模糊匹配默认会扫描全表,索引不生效。
语法
select "字段" from "表名" where "字段" like {
模式};
#例子
select * from laozi where store_name like '%os%';
1.9 、order by
按关键字排序
语法
select "字段" from "表名" [where "条件"] order by "字段" [asc, desc];
#asc 是按照升序进行排序的,是默认的排序方式。
#desc 是按降序方式进行排序。
#例子
select store_name,sales,date from laozi order by sales desc;
1.10、 group by ----汇总分组
-
对group by后面的字段的查询结果进行汇总分组,通常是结合聚合函数一起使用的。
-
group by 有一个原则,凡是在 group by 后面出现的字段,必须在 select 后面出现;
-
凡是在 select 后面出现的、且未在聚合函数中出现的字段,必须出现在 group by 后面。
语法
select "字段1", sum("字段2"<