mysql高级sql语句-全面

这篇具有很好参考价值的文章主要介绍了mysql高级sql语句-全面。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一.实验前准备

1.location表格创建

use class;
create table location (Region char(20),store_name char(20));
insert into location values('East','Boston');
insert into location values('East','New York');
insert into location values('West','Los Angeles');
insert into location values('West','Houston');

2.store_info表格创建

create table store_info (store_name char(20),sales int(10),Date char(10));
insert into store_info values('Los Angeles','1500','2020-12-05');
insert into store_info values('Houston','250','2020-12-07');
insert into store_info values('Los Angeles','300','2020-12-08');
insert into store_info values('Boston','700','2020-12-08');

二.常用查询

1. select(显示查询)

  • 显示表格中一个或数个字段的所有数据记录
select "字段" from "表名";
例:select store_name from store_info;
例:mysql> select store_name from store_info;
+-------------+
| store_name  |
+-------------+
| Los Angeles |
| Houston     |
| Los Angeles |
| Boston      |
+-------------+
4 rows in set (0.00 sec)

2. distinct(不重复查询)

select distinct "字段" from "表名";
例:select distinct store_name from store_info;
例:mysql> select distinct store_name from store_info;
+-------------+
| store_name  |
+-------------+
| Los Angeles |
| Houston     |
| Boston      |
+-------------+
3 rows in set (0.00 sec)

3. where(有条件查询)

select distinct store_name "字段" from "表名";
例:select distinct store_name from store_info;
例:mysql> select distinct store_name from store_info;
+-------------+
| store_name  |
+-------------+
| Los Angeles |
| Houston     |
| Boston      |
+-------------+
3 rows in set (0.00 sec)

4. and/or(且/或)

select "字段" from "表名" where "条件1" {[and|or] "条件2"} + ;
例:select store_name from store_info where sales > 1000 or ( sales < 500and sales > 200 );
例:mysql> select store_name from store_info where sales > 1000;
+-------------+
| store_name  |
+-------------+
| Los Angeles |
+-------------+
1 row in set (0.00 sec)

5. in (显示已知值的字段)

  • 在已知的字段数据取值范围内取值
select "字段" from "表名" where "字段" in ('值1', '值2', ...);
例:select * from store_info where store_name in ('Los Angeles', 'Houston');
例:mysql> select * from store_info where store_name in ('Los Angeles','Hoston');
+-------------+-------+------------+
| Store_Name  | Sales | Date       |
+-------------+-------+------------+
| Los Angeles |  1500 | 2020-12-05 |
| Los Angeles |   300 | 2020-12-08 |
+-------------+-------+------------+
2 rows in set (0.00 sec)

6. between(显示两个值范围内的字段)

  • 在两个字段数据值之间取值,包含两边字段的数据
select "字段" from "表名" where "字段"  between '值1' and '值2';
例:select * from store_info where Date between '2020-12-06' and '2020-12-10';
例:mysql> select * from store_info where date between '2020-12-06'
and '2020-12-10';
+-------------+-------+------------+
| Store_Name  | Sales | Date       |
+-------------+-------+------------+
| Houston     |   250 | 2020-12-07 |
| Los Angeles |   300 | 2020-12-08 |
| Boston      |   700 | 2020-12-08 |
+-------------+-------+------------+
3 rows in set (0.00 sec)

7. 通配符的使用

  • 通常通配符都是与like配合使用的
  • % :百分号表示零个、一个或多个字符
  • _ :下划线表示单个字符
名称 作用 举例
‘A_Z’ 所有以 ‘A’ 起头,另一个任何值的字符,且以 ‘Z’ 为结尾的字符串 ‘ABZ’ 和 'A2Z’符合而 ‘AKKZ’ 不符合
‘ABC%’ 所有以 ‘ABC’ 起头的字符串 ‘ABCD’ 和 ‘ABCABC’
‘%XYZ’ 所有以 ‘XYZ’ 结尾的字符串 ‘WXYZ’ 和 ‘ZZXYZ’
‘%AN%’ 所有含有 'AN’这个模式的字符串 ‘LOS ANGELES’ 和 ‘SAN FRANCISCO’
‘_AN%’ 所有第二个字母为 ‘A’ 和第三个字母为 ‘N’ 的字符串 ‘SAN FRANCISCO’ 符合而 ‘LOS ANGELES’ 不符合

8. like (匹配关键字查询)

select "字段" from "表名" where "字段" like {模式};
例:select * from store_info where store_name like%os%;
例:mysql> select * from store_info where store_name like '%os%';
+-------------+-------+------------+
| Store_Name  | Sales | Date       |
+-------------+-------+------------+
| Los Angeles |  1500 | 2020-12-05 |
| Los Angeles |   300 | 2020-12-08 |
| Boston      |   700 | 2020-12-08 |
+-------------+-------+------------+
3 rows in set (0.00 sec)

9. order by (按关键字排序)

select "字段" from "表名" [where “条件”] order by "字段" [ASC, DESC];   #ASC默认按照升序排序的;DESC是按降序排序的
例:select store_name,sales,Date from store_info order by sales DESC;
例:mysql> select store_name,sales,date from store_info order by sales DESC;
+-------------+-------+------------+
| store_name  | sales | date       |
+-------------+-------+------------+
| Los Angeles |  1500 | 2020-12-05 |
| Boston      |   700 | 2020-12-08 |
| Los Angeles |   300 | 2020-12-08 |
| Houston     |   250 | 2020-12-07 |
+-------------+-------+------------+
4 rows in set (0.00 sec)

三.常用函数

1. 数学函数

关键字 含义
abs(x) 返回 x 的绝对值
rand() 返回 0 到 1 的随机数
mod(x,y) 返回 x 除以 y 以后的余数
power(x,y) 返回 x 的 y 次方
round(x) 返回离 x 最近的整数
round(x,y) 保留 x 的 y 位小数四舍五入后的值
sqrt(x) 返回 x 的平方根
truncate(x,y) 返回数字 x 截断为 y 位小数的值
ceil(x) 返回大于或等于 x 的最小整数
floor(x) 返回小于或等于 x 的最大整数
greatest(x1,x2...) 返回集合中最大的值,也可以返回多个字段的最大的值
least(x1,x2…) 返回集合中最小的值,也可以返回多个字段的最小的值
  • 例1
select abs(-1), rand(), mod(5,3), power(2,3), round(1.89);
例:mysql> select abs(-1), rand(), mod(5,3), power(2,3), round(1.89);
+---------+---------------------+----------+------------+-------------+
| abs(-1) | rand()              | mod(5,3) | power(2,3) | round(1.89) |
+---------+---------------------+----------+------------+-------------+
|       1 | 0.04296933304795002 |        2 |          8 |           2 |
+---------+---------------------+----------+------------+-------------+
1 row in set (0.00 sec)
  • 例2
select round(1.8937,3), truncate(1.235,2), ceil(5.2), floor(2.1), least(1.89,3,6.1,2.1);
例:mysql> select round(1.8937,3), truncate(1.235,2), ceil(5.2), floor(2.1),least(1.89,3,6.1,2.1);
+-----------------+-------------------+-----------+------------+-----------------------+
| round(1.8937,3) | truncate(1.235,2) | ceil(5.2) | floor(2.1) | least(1.89,3,6.1,2.1) |
+-----------------+-------------------+-----------+------------+-----------------------+
|           1.894 |              1.23 |         6 |          2 |                  1.89 |
+-----------------+-------------------+-----------+------------+-----------------------+
1 row in set (0.00 sec)

2. 聚合函数

关键字 含义
avg() 返回指定列的平均值
count() 返回指定列中非 NULL 值的个数
min() 返回指定列的最小值
max() 返回指定列的最大值
sum(x) 返回指定列的所有值之和
  • 求平均值
select avg(sales) from store_info;
例:mysql> select avg(sales) from store_info;
+------------+
| avg(sales) |
+------------+
|   687.5000 |
+------------+
1 row in set (0.00 sec)
  • 求表中城市数量
select count(store_name) from store_info;
例:mysql> select count(store_name) from store_info;
+-------------------+
| count(store_name) |
+-------------------+
|                 4 |
+-------------------+
1 row in set (0.00 sec)
  • 统计数量,进行去重
select count(distinct store_name) from store_info;
例:mysql> select count(distinct store_name) from store_info;
+----------------------------+
| count(distinct store_name) |
+----------------------------+
|                          3 |
+----------------------------+
1 row in set (0.00 sec)
  • 统计字段中最大值
select max(sales) from store_info;
例:mysql> select max(sales) from store_info;
+------------+
| max(sales) |
+------------+
|       1500 |
+------------+
1 row in set (0.00 sec)
  • 统计字段中最小值
select min(sales) from store_info;
例:mysql> select min(sales) from store_info;
+------------+
| min(sales) |
+------------+
|        250 |
+------------+
1 row in set (0.00 sec)
  • 统计字段中的总和
select sum(sales) from store_info;
例:mysql> select sum(sales) from store_info;
+------------+
| sum(sales) |
+------------+
|       2750 |
+------------+
1 row in set (0.00 sec)

3. 字符串函数

关键字 含义
trim() 返回去除指定格式的值
concat(x,y) 将提供的参数 x 和 y 拼接成一个字符串
substr(x,y) 获取从字符串 x 中的第 y 个位置开始的字符串,跟substring()函数作用相同
substr(x,y,z) 获取从字符串 x 中的第 y 个位置开始长度为 z 的字符串
length(x) 返回字符串 x 的长度
replace(x,y,z) 将字符串 z 替代字符串 x 中的字符串 y
upper(x) 将字符串 x 的所有字母变成大写字母
lower(x) 将字符串 x 的所有字母变成小写字母
left(x,y) 返回字符串 x 的前 y 个字符
right(x,y) 返回字符串 x 的后 y 个字符
repeat(x,y) 将字符串 x 重复 y 次
``space(x)` 返回 x 个空格
strcmp(x,y) 比较 x 和 y,返回的值可以为-1,0,1
reverse(x) 将字符串 x 反转
  • 字段拼接

    • 示例1
    select concat(Region, store_name) from localtion where store_name = 'Boston';
    
    例:mysql> select concat(Region, store_name) from location where store_name = 'Boston';
    +----------------------------+
    | concat(Region, store_name) |
    +----------------------------+
    | EastBoston                 |
    +----------------------------+
    1 row in set (0.01 sec)
    
    • 示例2
    select Region || ' ' || store_name from localtion where store_name = 'Boston';
    
    例:mysql> select Region || ' ' || store_name from location where store_name = 'Boston';
    +-----------------------------+
    | Region || ' ' || store_name |
    +-----------------------------+
    | East Boston                 |
    +-----------------------------+
    1 row in set (0.00 sec)
    
    • 示例3
    select substr(store_name,3) from location where store_name = 'Los Angeles';
    
    例:mysql> select substr(store_name,3) from location where store_name = 'Los Angeles';
    +----------------------+
    | substr(store_name,3) |
    +----------------------+
    | s Angeles            |
    +----------------------+
    1 row in set (0.00 sec)
    
    • 示例4
    select substr(store_name,2,4) from location where store_name = 'New York';
    
    例:mysql> select substr(store_name,2,4) from location where store_name = 'New York';
    +------------------------+
    | substr(store_name,2,4) |
    +------------------------+
    | ew Y                   |
    +------------------------+
    1 row in set (0.00 sec)
    
  • 字段移除

    • 示例1
    select trim ([ [位置] [要移除的字符串] from ] 字符串);
    例:select trim(leading 'Ne ' from 'New York');
    
    例:mysql> select TRIM(LEADinG 'Ne' from 'New York');
    +------------------------------------+
    | TRIM(LEADinG 'Ne' from 'New York') |
    +------------------------------------+
    | w York                             |
    +------------------------------------+
    1 row in set (0.00 sec)
    
    • 示例2
    select Region,length(store_name) from location;
    
    例:mysql> select Region,length(store_name) from location;
    +--------+--------------------+
    | Region | length(store_name) |
    +--------+--------------------+
    | East   |                  6 |
    | East   |                  8 |
    | West   |                 11 |
    | West   |                  7 |
    +--------+--------------------+
    4 rows in set (0.00 sec)
    
    • 示例3
    select REPLACE(Region,'ast','astern')from location;
    
    例:mysql> select REPLACE(Region,'ast','astern')from location;
    +--------------------------------+
    | REPLACE(Region,'ast','astern') |
    +--------------------------------+
    | Eastern                        |
    | Eastern                        |
    | West                           |
    | West                           |
    +--------------------------------+
    4 rows in set (0.01 sec)
    

四.查询与函数

1. group by(汇总分组)

  • 对GROUP by后面的栏位的查询结果进行汇总分组,通常是结合聚合函数一起使用的
  • GROUP by有一个原则,就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在GROUP by后面
select "字段1", SUM("字段2") from "表名" GROUP by "字段1";
例:select store_name,sum(sales) from store_info group by store_name order by sales desc;
例:mysql> select store_name, SUM(sales) from store_info GROUP by store_name order by sales desc;
+-------------+------------+
| store_name  | SUM(sales) |
+-------------+------------+
| Los Angeles |       1800 |
| Boston      |        700 |
| Houston     |        250 |
+-------------+------------+
3 rows in set (0.00 sec)

2. having(过滤返回值)

  • 用来过滤由 GROUP by 语句返回的记录集,通常与 GROUP by 语句联合使用
  • HAVinG 语句的存在弥补了 where 关键字不能与聚合函数联合使用的不足
select "字段1", SUM("字段2") from "表格名" GROUP by "字段1" HAVinG (函数条件);
例:select store_name, SUM(sales) from store_info group up store_name having SUM(sales) > 1500;
例:mysql> select store_name, SUM(sales) from store_info GROUP by store_name HAVinG SUM(sales) > 1500;
+-------------+------------+
| store_name  | SUM(sales) |
+-------------+------------+
| Los Angeles |       1800 |
+-------------+------------+
1 row in set (0.00 sec)

3. 别名(字段别名 表格别名)

select "表格別名"."字段1" [AS] "字段別名" from "表格名" [AS] "表格別名";
例:select A.store_name Store, SUM(A.sales) "Total sales" from store_info A group by A.store_name;
例:mysql> select A.store_name store, SUM(A.sales) "Total sales" from store_info A GROUP by A.store_name;
+-------------+-------------+
| store       | Total sales |
+-------------+-------------+
| Boston      |         700 |
| Houston     |         250 |
| Los Angeles |        1800 |
+-------------+-------------+
3 rows in set (0.00 sec)

4. 子查询

  • 连接表格,在where 子句或 HAVinG 子句中插入另一个 SQL 语句
select "字段1" from "表格1" where "字段2" [比较运算符] 	#外查询
(select "字段1" from "表格2" where "条件");      #内查询
  • 查询两个表交集的城市
select * from location where store_name in (select store_name from store_info);
例:mysql> select * from location where store_name in (select store_name from store_info);
+--------+-------------+
| Region | Store_Name  |
+--------+-------------+
| West   | Los Angeles |
| West   | Houston     |
| East   | Boston      |
+--------+-------------+
3 rows in set (0.00 sec)

  • 查询在location表中西部城市的销售总和
select sum(sales) from store_info where store_name in (select store_name from location where region = 'West');
例:mysql> select SUM(sales) from store_info where store_name in 
    -> (select store_name from location where Region = 'West');
+------------+
| SUM(sales) |
+------------+
|       2050 |
+------------+
1 row in set (0.00 sec)
  • 通过多表查询,查询两个表中有交集的值
select sum(A.sales) from store_info A where A.store_name in 
(select store_name from location B where B.store_name = A.store_name);
例:mysql> select SUM(A.sales) from store_info A where A.store_name in 
    -> (select store_name from location B where B.store_name = A.store_name);
+--------------+
| SUM(A.sales) |
+--------------+
|         2750 |
+--------------+
1 row in set (0.00 sec)

5. exists(类查询)

  • 用来测试内查询有没有产生任何结果,类似布尔值是否为真
  • 如果有的话,系统就会执行外查询中的SQL语句。若是没有的话,那整个 SQL 语句就不会产生任何结果
select "字段1" from "表格1" where exists (select * from "表格2" where "条件");
例:select SUM(sales) from store_info where exists (select * from location where Region = 'West');
例:mysql> select SUM(sales) from store_info where exists (select * from location where region = 'West');
+------------+
| SUM(sales) |
+------------+
|       2750 |
+------------+
1 row in set (0.00 sec)

五.连接查询

1.inner join(内连接)

  • 只返回两个表中联结字段相等的行

  • 示例一

select * from location A inner join store_info B on A.store_name = B.store_name ;
例:mysql> select * from location A inner join store_info B on A.store_name = B.store_name ;
+--------+-------------+-------------+-------+------------+
| Region | Store_Name  | Store_Name  | Sales | Date       |
+--------+-------------+-------------+-------+------------+
| West   | Los Angeles | Los Angeles |  1500 | 2020-12-05 |
| West   | Houston     | Houston     |   250 | 2020-12-07 |
| East   | Boston      | Boston      |   700 | 2020-12-08 |
+--------+-------------+-------------+-------+------------+
3 rows in set (0.00 sec)
  • 示例二
select * from location A, store_info B where A.store_name = B.store_name;
例:mysql> select * from location A, store_info B where A.store_name = B.store_name;
+--------+-------------+-------------+-------+------------+
| Region | Store_Name  | Store_Name  | Sales | Date       |
+--------+-------------+-------------+-------+------------+
| West   | Los Angeles | Los Angeles |  1500 | 2020-12-05 |
| West   | Houston     | Houston     |   250 | 2020-12-07 |
| East   | Boston      | Boston      |   700 | 2020-12-08 |
+--------+-------------+-------------+-------+------------+
3 rows in set (0.00 sec)
  • 示例三
select A.region region, sum(B.sales) sales from location A, store_info B 
where A.store_name = B.store_name group by region;
例:mysql> select A.region region, sum(B.sales) sales from location A, store_info B 
    -> where A.store_name = B.store_name group by region;
+--------+-------+
| region | sales |
+--------+-------+
| East   |   700 |
| West   |  1750 |
+--------+-------+
2 rows in set (0.00 sec)

2.left join(左连接)

  • 返回包括左表中的所有记录和右表中联结字段相等的记录
select * from location A left join store_info B on A.store_name = B.store_name ;
例:mysql> select * from location A left join store_info B on A.store_name = B.store_name ;
+--------+-------------+-------------+-------+------------+
| Region | Store_Name  | Store_Name  | Sales | Date       |
+--------+-------------+-------------+-------+------------+
| West   | Los Angeles | Los Angeles |  1500 | 2020-12-05 |
| West   | Houston     | Houston     |   250 | 2020-12-07 |
| East   | Boston      | Boston      |   700 | 2020-12-08 |
| East   | New York    | NULL        |  NULL | NULL       |
+--------+-------------+-------------+-------+------------+
4 rows in set (0.00 sec)

3.right join(右连接)

  • 返回包括右表中的所有记录和左表中联结字段相等的记录
select * from location A right join store_info B on A.store_name = B.store_name ;
例:mysql> select * from location A right join store_info B on A.store_name = B.store_name ;
+--------+-------------+-------------+-------+------------+
| Region | Store_Name  | Store_Name  | Sales | Date       |
+--------+-------------+-------------+-------+------------+
| East   | Boston      | Boston      |   700 | 2020-12-08 |
| West   | Los Angeles | Los Angeles |  1500 | 2020-12-05 |
| West   | Houston     | Houston     |   250 | 2020-12-07 |
| NULL   | NULL        | Washington  |   300 | 2020-12-08 |
+--------+-------------+-------------+-------+------------+
4 rows in set (0.00 sec)

4.create view (视图虚拟表或存储查询)

  • 视图跟表格的不同是,表格中有实际储存数据记录,而视图是建立在表格之上的一个架构,它本身并不实际储存数据记录
  • 临时表在用户退出或同数据库的连接断开后就自动消失了,而视图不会消失
  • 视图不含有数据,只存储它的定义,它的用途一般可以简化复杂的查询。比如你要对几个表进行连接查询,而且还要进行统计排序等操作,写SQL语句会很麻烦的,用视图将几个表联结起来,然后对这个视图进行查询操作,就和对一个表查询一样,很方便
create view "视图表名" as "select 语句";
例:create view V_region_sales as select A.region region,sum(B.sales) sales from location A inner join store_info B on A.store_name = B.store_name group by region;
select * from V_region_sales;
drop view V_region_sales;
例:mysql> create view V_region_sales as select A.region region,sum(B.sales)sales from location A
    -> inner join store_info B on A.store_name = B.store_name group by region;
Query OK, 0 rows affected (0.01 sec)
mysql> select * from V_region_sales;
+--------+-------+
| region | sales |
+--------+-------+
| East   |   700 |
| West   |  1750 |
+--------+-------+
2 rows in set (0.00 sec)
mysql> drop view V_region_sales;
Query OK, 0 rows affected (0.00 sec)

5.union(联集)

  • 将两个SQL语句的结果合并起来,两个SQL语句所产生的字段需要是同样的数据记录种类
  • 生成结果的数据记录值将没有重复,且按照字段的顺序进行排序

union 用法

[select 语句 1] union [select 语句 2];
select store_name from location union select store_name from store_info;
例:mysql> select store_name from location union select store_name from store_info;
+-------------+
| store_name  |
+-------------+
| Boston      |
| New York    |
| Los Angeles |
| Houston     |
| Washington  |
+-------------+
5 rows in set (0.00 sec)

union all 用法

[select 语句 1] union all [select 语句 2];
select store_name from location union all select store_name from store_info;
例:mysql> select store_name from location union all select store_name from store_info;
+-------------+
| store_name  |
+-------------+
| Boston      |
| New York    |
| Los Angeles |
| Houston     |
| Los Angeles |
| Houston     |
| Washington  |
| Boston      |
+-------------+
8 rows in set (0.00 sec)

6.交集值

① 取两个SQL语句结果的交集

select A.store_name from location A inner join store_info B on A.store_name = B.store_name;
例:mysql> select A.store_name from location A inner join store_info B on A.store_name = B.store_name;
+-------------+
| store_name  |
+-------------+
| Los Angeles |
| Houston     |
| Boston      |
+-------------+
3 rows in set (0.00 sec)
select A.store_name from location A inner join store_info B using(store_name);
例:mysql> select A.store_name from location A inner join store_info B using(store_name);
+-------------+
| store_name  |
+-------------+
| Los Angeles |
| Houston     |
| Boston      |
+-------------+
3 rows in set (0.00 sec)

② 取两个SQL语句结果的交集,且没有重复

select DISTINCT A.store_name from location A inner join store_info B using(store_name);

select DISTINCT store_name from location where (store_name) IN (select store_name from store_info);

select DISTINCT A.store_name from location A left join store_info B using(store_name) where B.store_name IS NOT NULL;

select A.store_name from (select B.store_name from location B inner join store_info C on B.store_name = C.store_name) A 
group by A.store_name;

例:mysql> select distinct A.store_name from location A inner join store_info B using(store_name);
+-------------+
| store_name  |
+-------------+
| Los Angeles |
| Houston     |
| Boston      |
+-------------+
3 rows in set (0.01 sec)

mysql> select distinct store_name from location where (store_name) in (select store_name from store_info);
+-------------+
| store_name  |
+-------------+
| Los Angeles |
| Houston     |
| Boston      |
+-------------+
3 rows in set (0.00 sec)

mysql> select distinct A.store_name from location A left join store_info B using(store_name)where B.store_name is not null;
+-------------+
| store_name  |
+-------------+
| Boston      |
| Los Angeles |
| Houston     |
+-------------+
3 rows in set (0.01 sec)

mysql> select A.store_name from (select B.store_name from location B inner join store_info C on B.store_name = C.store_name)A
    -> group by A.store_name;
+-------------+
| store_name  |
+-------------+
| Boston      |
| Houston     |
| Los Angeles |
+-------------+
3 rows in set (0.00 sec)

mysql> select A.store_name from 
    -> (select distinct store_name from location union all select distinct store_name from store_info)A
    -> group by A.store_name having count(*) > 1;
+-------------+
| store_name  |
+-------------+
| Boston      |
| Houston     |
| Los Angeles |
+-------------+
3 rows in set (0.01 sec)

7.无交集值

① 显示第一个SQL语句的结果,且与第二个SQL语句没有交集的结果,且没有重复

select DISTINCT store_name from location where (store_name) NOT IN (select store_name from store_info);
例:mysql> select distinct store_name from location where (store_name) not in (select store_name from store_info);
+------------+
| store_name |
+------------+
| New York   |
+------------+
1 row in set (0.00 sec)
select DISTINCT A.store_name from location A left join store_info B using(store_name) where B.store_name IS NULL;
例:mysql> select distinct A.store_name from location A left join store_info B using(store_name) where B.store_name is null;
+------------+
| store_name |
+------------+
| New York   |
+------------+
1 row in set (0.00 sec)
select A.store_name from 
(select DISTINCT store_name from location union all select DISTINCT store_name from store_info) A 
group by A.store_name HAVING COUNT(*) = 1;
例:mysql> select A.store_name from 
    -> (select distinct store_name from location union all select distinct store_name from store_info)A
    -> group by A.store_name having count(*) = 1;
+------------+
| store_name |
+------------+
| New York   |
| Washington |
+------------+
2 rows in set (0.00 sec)

8.Case

① 是 SQL 用来做为 if-then-ELSE 之类逻辑的关键字

select Case ("字段名")
  when "条件1" then "结果1"     # "条件" 可以是一个数值或是公式。 ELSE 子句则并不是必须的。
  when "条件2" then "结果2"
  ...
  [ELSE "结果N"]
  end
from "表名";
例:select store_name, Case store_name 
  when 'Los Angeles' then sales * 2 
  when 'Boston' then 2000
  ELSE sales 
  end 
"New sales",Date    #"New sales" 是用于 Case 那个字段的字段名。
from store_info;
例:mysql> select store_name, Case store_name 
    ->   WHEN 'Los Angeles' THEN sales * 2 
    ->   WHEN 'Boston' THEN 2000
    ->   ELSE sales 
    ->   END 
    -> "New sales",Date 
    -> from store_info;
+-------------+-----------+------------+
| store_name  | New sales | Date       |
+-------------+-----------+------------+
| Los Angeles |      3000 | 2020-12-05 |
| Houston     |       250 | 2020-12-07 |
| Washington  |       300 | 2020-12-08 |
| Boston      |      2000 | 2020-12-08 |
+-------------+-----------+------------+
4 rows in set (0.00 sec)

9.空值(NULL) 和 无值(‘’) 的区别

① 无值的长度为 0,不占用空间的;而 NULL 值的长度是 NULL,是占用空间的

② IS NULL 或者 IS NOT NULL,是用来判断字段是不是为 NULL 或者不是 NULL,不能查出是不是无值的。
无值的判断使用='‘或者<>’'来处理。<> 代表不等于

③ 在通过 count()指定字段统计有多少行数时,如果遇到 NULL 值会自动忽略掉,遇到无值会加入到记录中进行计算

示例一

select length(NULL), length(''), length('1');
select * from City where name IS NULL;
select * from City where name IS NOT NULL;
select * from City where name = '';
select * from City where name <> '';
select COUNT(*) from City;c
select COUNT(name) from City;
例:mysql> SELECT length(NULL), length(''), length('1');
+--------------+------------+-------------+
| length(NULL) | length('') | length('1') |
+--------------+------------+-------------+
|         NULL |          0 |           1 |
+--------------+------------+-------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM city WHERE name IS NULL;
Empty set (0.00 sec)

mysql> SELECT * FROM city WHERE name IS NOT NULL;
+----------+
| name     |
+----------+
| beijing  |
| nanjing  |
| shanghai |
| <null>   |
| <null>   |
+----------+
5 rows in set (0.00 sec)

mysql> SELECT * FROM city WHERE name = '';
Empty set (0.00 sec)

mysql> SELECT * FROM city WHERE name <> '';
+----------+
| name     |
+----------+
| beijing  |
| nanjing  |
| shanghai |
| <null>   |
| <null>   |
+----------+
5 rows in set (0.00 sec)

mysql> SELECT COUNT(*) FROM city;
+----------+
| COUNT(*) |
+----------+
|        5 |
+----------+
1 row in set (0.00 sec)

mysql> SELECT COUNT(name) FROM city;
+-------------+
| COUNT(name) |
+-------------+
|           5 |
+-------------+
1 row in set (0.00 sec)

10.正则表达式

匹配模式 描述 实例
^ 匹配文本的开始字符 ‘^bd’ 匹配以 bd 开头的字符串
$ 匹配文本的结束字符 ‘qn$’ 匹配以 qn 结尾的字符串
. 匹配任何单个字符 ‘s.t’ 匹配任何 s 和 t 之间有一个字符的字符串
* 匹配零个或多个在它前面的字符 ‘fo*t’ 匹配 t 前面有任意个 o
+ 匹配前面的字符 1 次或多次 ‘hom+’ 匹配以 ho 开头,后面至少一个m 的字符串
字符串 匹配包含指定的字符串 ‘clo’ 匹配含有 clo 的字符串
p1|p2 匹配 p1 或 p2 ‘bg|fg’ 匹配 bg 或者 fg
[…] 匹配字符集合中的任意一个字符 ‘[abc]’ 匹配 a 或者 b 或者 c
[^…] 匹配不在括号中的任何字符 ‘[ ^ ab]’ 匹配不包含 a 或者 b 的字符串
{n} 匹配前面的字符串 n 次 ‘g{2}’ 匹配含有 2 个 g 的字符串
{n,m} 匹配前面的字符串至少 n 次 至多m 次 ‘f{1,3}’ 匹配 f 最少 1 次,最多 3 次
select "字段" from "表名" where "字段" REGEXP {模式};
例:select * from store_info where store_name REGEXP 'os';
select * from store_info where store_name REGEXP '^[A-G]';
select * from store_info where store_name REGEXP 'Ho|Bo';
例:mysql> SELECT * FROM store_info WHERE Store_Name REGEXP 'os';
+-------------+-------+------------+
| Store_Name  | Sales | Date       |
+-------------+-------+------------+
| Los Angeles |  1500 | 2020-12-05 |
| Boston      |   700 | 2020-12-08 |
+-------------+-------+------------+
2 rows in set (0.00 sec)

mysql> SELECT * FROM store_info WHERE Store_Name REGEXP '^[A-G]';
+------------+-------+------------+
| Store_Name | Sales | Date       |
+------------+-------+------------+
| Boston     |   700 | 2020-12-08 |
+------------+-------+------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM store_info WHERE Store_Name REGEXP 'Ho|Bo';
+------------+-------+------------+
| Store_Name | Sales | Date       |
+------------+-------+------------+
| Houston    |   250 | 2020-12-07 |
| Boston     |   700 | 2020-12-08 |
+------------+-------+------------+
2 rows in set (0.00 sec)

六.存储过程

1.存储过程介绍

① 存储过程是一组为了完成特定功能的SQL语句集合

② 存储过程在使用过程中是将常用或者复杂的工作预先使用SQL语句写好并用一个指定的名称存储起来,这个过程经编译和优化后存储在数据库服务器中。当需要使用该存储过程时,只需要调用它即可。存储过程在执行上比传统SQL速度更快、执行效率更高

2.存储过程的优点

① 执行一次后,会将生成的二进制代码驻留缓冲区,提高执行效率

② SQL语句加上控制语句的集合,灵活性高

③ 在服务器端存储,客户端调用时,降低网络负载

④ 可多次重复被调用,可随时修改,不影响客户端调用

⑤ 可完成所有的数据库操作,也可控制数据库的信息访问权限

3.创建存储过程

示例一

delimiter $$						#将语句的结束符号从分号;临时改为两个$$(可以是自定义)
create procedure proc()				#创建存储过程,过程名为proc,不带参数
-> begin							#过程体以关键字 begin 开始
-> select * from store_info;		#过程体语句
-> end $$							#过程体以关键字 end 结束
delimiter ;							#将语句的结束符号恢复为分号
例:mysql> delimiter $$
mysql> create procedure proc()
    -> begin
    -> select * from store_info;
    -> end $$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

4.调用存储过程

示例一

call proc;
例:mysql> call proc;
+-------------+-------+------------+
| Store_Name  | Sales | Date       |
+-------------+-------+------------+
| Los Angeles |  1500 | 2020-12-05 |
| Houston     |   250 | 2020-12-07 |
| Washington  |   300 | 2020-12-08 |
| Boston      |   700 | 2020-12-08 |
+-------------+-------+------------+
4 rows in set (0.01 sec)
Query OK, 0 rows affected (0.01 sec)

5.查看存储过程

  • 示例一
show create procedure [数据库.]存储过程名;		#查看某个存储过程的具体信息
例:mysql> show create procedure tour.proc;
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| Procedure | sql_mode                                                                                                                                                                 | Create Procedure                                                                         | character_set_client | collation_connection | Database Collation |
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| proc      | PIPES_AS_CONCAT,ANSI_QUOTES,NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION | CREATE DEFINER="root"@"localhost" PROCEDURE "proc"()
begin
select * from store_info;
end | utf8                 | utf8_general_ci      | utf8_general_ci    |
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
  • 示例二
show create procedure proc;
例:mysql> show create procedure proc;
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| Procedure | sql_mode                                                                                                                                                                 | Create Procedure                                                                         | character_set_client | collation_connection | Database Collation |
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| proc      | PIPES_AS_CONCAT,ANSI_QUOTES,NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION | CREATE DEFINER="root"@"localhost" PROCEDURE "proc"()
begin
select * from store_info;
end | utf8                 | utf8_general_ci      | utf8_general_ci    |
+-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
  • 示例三
show procedure status [like '%proc%'] \G
例:mysql> show procedure status like '%proc%'\G
*************************** 1. row ***************************
                  Db: tour
                Name: proc
                Type: PROCEDURE
             Definer: root@localhost
            Modified: 2023-06-23 16:00:23
             Created: 2023-06-23 16:00:23
       Security_type: DEFINER
             Comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
1 row in set (0.01 sec)

6.存储过程的参数

① in 输入参数:表示调用者向过程传入值(传入值可以是字面量或变量)

② out 输出参数:表示过程向调用者传出值(可以返回多个值)(传出值只能是变量)

③ inout 输入输出参数:既表示调用者向过程传入值,又表示过程向调用者传出值(值只能是变量)

  • 示例一
delimiter $$				
create procedure proc1(in inname char(16))		
-> begin					
-> select * from store_info where store_name = inname;
-> end $$					
delimiter ;					
call proc1('Boston');
例:mysql> delimiter $$
mysql> create procedure proc1(in inname char(16))
    -> begin
    -> select *from store_info where store_name = inname;
    -> end $$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call proc1('boston');
+------------+-------+------------+
| Store_Name | Sales | Date       |
+------------+-------+------------+
| Boston     |   700 | 2020-12-08 |
+------------+-------+------------+
1 row in set (0.01 sec)
Query OK, 0 rows affected (0.01 sec)
  • 示例二
delimiter $$
mysql> create procedure proc3(in myname char(10), out outname int)
    -> begin
    -> select sales into outname from t1 where name = myname;
    -> end $$
delimiter ;
call proc3('yzh', @out_sales);
select @out_sales;
例:mysql> delimiter $$
mysql> create procedure proc3(in myname char(10),out outname int)
    -> begin
    -> select sales into outname from t1 where name=myname;
    -> end $$
Query OK, 0 rows affected (0.00 sec)
  • 示例三
mysql>  create table t(id int(10));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into t values(10);
Query OK, 1 row affected (0.00 sec)
delimiter $$
mysql> create procedure proc4(inout insales int)
    -> begin
    -> select count(sales) into insales from t1 where sales < insales;
    -> end $$
delimiter ;
set @inout_sales=1000;
call proc4(@inout_sales);
select @inout_sales;
例:mysql> delimiter $$
mysql> create procedure proc4(inout insales int)
    -> begin
    -> select count(sales) into insales from t1 where sales < insales;
    -> end $$
Query OK, 0 rows affected (0.01 sec)

mysql> delimiter ;
mysql> set @inout_sales=1000;
Query OK, 0 rows affected (0.00 sec)

mysql> call proc4(@inout_sales);
Query OK, 1 row affected (0.00 sec)

mysql> select @inout_sales;
+--------------+
| @inout_sales |
+--------------+
|            5 |
+--------------+
1 row in set (0.00 sec)

7.删除存储过程

① 存储过程内容的修改方法是通过删除原有存储过程,之后再以相同的名称创建新的存储过程。如果要修改存储过程的名称,可以先删除原存储过程,再以不同的命名创建新的存储过程

  • 示例一
drop procedure if exists proc;		#仅当存在时删除,不添加 if exists 时,如果指定的过程不存在,则产生一个错误
例:mysql> drop procedure if exists proc4;
Query OK, 0 rows affected (0.00 sec)

8.存储过程的控制语句

  • 示例一
create table t (id int(10));
insert into t values(10);
mysql> delimiter $$
mysql> create procedure proc2(in pro int)
    -> begin 
    -> declare var int;
    -> set var=pro*2;
    -> if var>=10 then
    -> update t set id=id+1;
    -> else
    -> update t set id=id-1;
    -> end if;
    -> end $$
Query OK, 0 rows affected (0.01 sec)

① 条件语句

if-then-else ···· end if 
delimiter $$  
create procedure proc2(in pro int)  
-> begin 
-> declare var int;  
-> set var=pro*2;   
-> if var>=10 then 
-> update t set id=id+1;  
-> else 
-> update t set id=id-1;  
-> end if;  
-> end $$
delimiter ;
call proc2(6);

② 循环语句文章来源地址https://www.toymoban.com/news/detail-500603.html

while ···· end while
delimiter $$  
create procedure proc3()
-> begin 
-> declare var int(10);  
-> set var=0;  
-> while var<6 do  
-> insert into t values(var);  
-> set var=var+1;  
-> end while;  
-> end $$  
delimiter ;
call proc3;
mysql> delimiter $$
mysql> create procedure proc9()
    -> begin
    -> declare var int(10);
    -> set var=0;
    -> while var<6 do
    -> insert into t values(var);
    -> set var=var+1;
    -> end while;
    -> end $$
Query OK, 0 rows affected (0.00 sec)

到了这里,关于mysql高级sql语句-全面的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • MySQL高级(进阶)SQL语句

    #显示一个字段或者多个字段的所有内容 SELECT “字段” FROM 表名 ; #distinct对字段去重查询 (最好只对单个字段进行去重) SELECT DISTINCT 字段名 FROM 表名 #where 有条件查询 SELECT “字段” FROM 表名 WHERE 条件(例如:sales =!= 100); #and or 查看多个条件 SELECT “字段” FROM 表名 WHE

    2024年02月05日
    浏览(43)
  • MySQL 数据库实用指南:测试数据准备、SQL语句规范与基本操作

    欢迎来到小K的MySQL专栏,本节将为大家准备MySQL测试数据、以及带来SQL语句规范、数据库的基本操作的详细讲解 要学习SQL查询语句,首先必须解决一个问题,数据问题。为了方便大家学习阅读我的文章,在这里提供了一个test.sql文件 ✨ 登录MySQL,输入 source xxx/test.sql 导入sql文

    2024年02月08日
    浏览(82)
  • MySQL 高级(进阶) SQL 语句二

    MYSQL数据库中的三种连接: inner join(内连接):只返回两个表中联结字段相等的行(有交集的值) left join(左连接):返回包括左表中的所有记录和右表中联结字段相等的记录 right join(右连接):返回包括右表中的所有记录和左表中联结字段相等的记录 注:oracle数据库支持 outer

    2024年02月07日
    浏览(44)
  • MySQL中的SQL高级语句[一](上篇)

    使用语言  MySQL 使用工具  Navicat Premium 16 代码能力快速提升小方法,看完代码自己敲一遍,十分有用 拖动表名到查询文件中就可以直接把名字拉进来 以下是使用脚本方法,也可以直接进行修改 中括号,就代表可写可不写  目录 1.修改数据表结构 1.1 修改数据库的表名  1.

    2024年04月14日
    浏览(48)
  • 【MySQL数据库】MySQL 高级SQL 语句一

    ) % :百分号表示零个、一个或多个字符 _ :下划线表示单个字符 ‘A_Z’:所有以 ‘A’ 起头,另一个任何值的字符,且以 ‘Z’ 为结尾的字符串。例如,‘ABZ’ 和 ‘A2Z’ 都符合这一个模式,而 ‘AKKZ’ 并不符合 (因为在 A 和 Z 之间有两个字符,而不是一个字符)。 ‘ABC%’

    2024年02月09日
    浏览(241)
  • 【数据库】MySQL 高级(进阶) SQL 语句

    location表格创建 store_info表格创建 显示表格中一个或数个字段的所有数据记录 不显示重复的数据记录 按照条件进行查询 在已知的字段数据取值范围内取值 另外还有not in命令,用法一致,表示显示不在指定范围内的字段的值。 在两个字段数据值之间取值,包含两边字段的数据

    2024年02月09日
    浏览(136)
  • Linux5.7 MySQL 高级(进阶) SQL 语句

    第四章 LINUX MySQL 高级(进阶) SQL 语句 一、高级SQL 语句 1.SELECT 显示表格中一个或数个字段的所有数据记录 2.DISTINCT 不显示重复的数据记录 3.WHERE 有条件查询 4.AND OR 且 或 5.IN 显示已知的值的数据记录 6.BETWEEN 显示两个值范围内的数据记录 7.通配符 通常通配符都是跟 LIKE 一起使用

    2024年02月09日
    浏览(50)
  • 数据库应用:MySQL数据库SQL高级语句与操作

    目录 一、理论 1.克隆表与清空表 2.SQL高级语句 3.SQL函数 4.SQL高级操作 5.MySQL中6种常见的约束 二、实验  1.克隆表与清空表 2.SQL高级语句 3.SQL函数 4.SQL高级操作 5.主键表和外键表  三、总结 克隆表:将数据表的数据记录生成到新的表中。 (1)克隆表 ① 先创建再导入 ② 创建

    2024年02月13日
    浏览(81)
  • 高级SQL语句

    ---- SELECT ---- 显示表格中一个或数个字段的所有数据记录 语法:SELECT “字段” FROM “表名”; ---- DISTINCT ---- 不显示重复的数据记录 语法:SELECT DISTINCT “字段” FROM “表名”; ---- WHERE ---- 有条件查询 语法:SELECT “字段” FROM “表名” WHERE “条件”; ---- AND OR ---- 且 或 语法:

    2024年02月10日
    浏览(37)
  • 数据库SQL语句如何在表格里增加一条数据

    语法为:insert into 表名(col1,col2...)values(value1,value2...); insert into :插入  + 表名(例如users)+列名+values(值) 例如: 注意:列中的类型需要和value一一对应,如果类型不对应会提示报错。 value后的内容可以添加多行 例如 运行环境dos:   检验: 通过查询语句检查是否成功

    2024年02月12日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包