MySQL- Advanced Search

Nested queries (subqueries)

The query result as the outer layer of the inner query

select ... from 表名 where 条件(select ....);
Examples
# 把攻击值小于平均攻击值的英雄名字和攻击值显示出来
select name,gongji from MOSHOU.sanguo
where 
gongji<(select avg(gongji) from MOSHOU.sanguo);
# 找出每个国家攻击力最高的英雄的名字和攻击值
select name,gongji from moshou.sanguo
where 
(country,gongji) in
(select country,max(gongji) from moshou.sanguo group by country);

Multi-table query

Joint inquiry between multiple tables

// 方式一
select 字段名列表 from 表名列表; (笛卡尔积)
/*
t1 : name -> "A1"  "A2"  "A3"
t2 : name -> "B1"  "B2"
select * from t1,t2;
+------+-------+
| name | name2 |
+------+-------+
| A1   | B1    |
| A1   | B2    |
| A2   | B1    |
| A2   | B2    |
| A3   | B1    |
| A3   | B2    |
+------+-------+
*/

// 方式二
... where 条件
// 显示省和市的详细信息
select sheng.s_name,city.c_name from sheng,city
where
sheng.s_id=city.cfather_id;
// 显示省市县详细信息
select sheng.s_name,city.c_name,xian.x_name from sheng,city,xian
where
sheng.s_id=city.cfather_id and city.c_id = xian.xfather_id;

Join query

En
# 语法格式
select 字段名 from 表1 inner join 表2 on 条件 inner join 表3 on 条件;

# 显示省市详细信息
select sheng.s_name,city.c_name from sheng 
inner join city on sheng.s_id = city.cfather_id;
# 显示省市县详情信息
select sheng.s_name,city.c_name,xian.x_name from sheng 
inner join city on sheng.s_id = city.cfather_id
inner join xian on city.c_id = xian.xfather_id;
Outer join

To the left (right) table-based display query results, record the left (right) side of the show all

# 语法格式
select 字段名 from 表1 
left(right) join 表2 on 条件 
left(right) join 表3 on 条件;

# 显示省市详细信息
select sheng.s_name,city.c_name from sheng
left join city on sheng.s_id = city.cfather_id;
# 显示省市县详情信息
select sheng.s_name,city.c_name,xian.x_name from sheng
left join city on sheng.s_id = city.cfather_id
left join xian on city.c_id - xian.xfather_id;

Reproduced in: https: //www.jianshu.com/p/603bedf28c44

Guess you like

Origin blog.csdn.net/weixin_34122548/article/details/91228927