前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Mysql 高级操作

Mysql 高级操作

作者头像
嘉美伯爵
发布2021-01-18 10:55:37
7570
发布2021-01-18 10:55:37
举报

连接

inner join(内连接)

  • 两个表都存在匹配时,返回行
  • 查询每个学生,每个科目的成绩
代码语言:javascript
复制
select students.sname, subjects.stitle, scores.score
from scores
inner join students on scores.stuid = students.id
inner join subjects on scores.subid = subjects.id;
### 如下
+-------+--------+-------+
| sname | stitle | score |
+-------+--------+-------+
| Gage  | 语文   | 90.00 |
+-------+--------+-------+

left join(左连接)

  • 返回左表中的所有数据,即使右表中没有匹配的数据

查询每个学生的平均成绩

代码语言:javascript
复制
select students.sname, avg(scores.score)
from scores
left join students on scores.stuid = students.id
group by students.sname;

返回右表中的所有数据,即使左表中没有匹配的数据

full join (全连接)

  • 只要一个表存在匹配就返回

自关联

对于省市区表,我们可以采用一对多的形式建立三张表,但这样会带来不必要开销,分析后发现 省份无上级,我们建立三个字段,id为省份id, pid为市区id,这样只要让pid=id就可以使省市区关联起来

定义数据表

查询山东省下的所以市区

查询省市区

内置函数

对于复杂的一些查询,每次书写查询语句相当麻烦。我们可以定义视图

子查询

普通查询

  • 查询每位学生的各科成绩
代码语言:javascript
复制
mysql> select sname as 姓名,
    -> (select scores.score from scores inner join subjects on subjects.id=scores.subid where subjects.stitle="语文"  and students.id=scores.stuid)  as 语文,
    -> (select scores.score from scores inner join subjects on subjects.id=scores.subid where subjects.stitle="数学"  and students.id=scores.stuid)  as 数学
    -> from students;
+--------+--------+--------+
| 姓名   | 语文   | 数学   |
+--------+--------+--------+
| Gage   |  90.00 |  54.00 |
| sss    |   NULL |   NULL |
| kksk   |   NULL |   NULL |
+--------+--------+--------+

比较查询

  • 查询数学成绩大于85的学生
代码语言:javascript
复制
select sname as 姓名, 
(select scores.score from scores inner join subjects on subjects.id=scores.subid where subjects.stitle="数学"  and students.id=scores.stuid and score>85)  as 数学
from students;
+--------+--------+
| 姓名   | 数学   |
+--------+--------+
| Gage   |  98.00 |
| sss    |  86.00 |
| kksk   |   NULL |
+--------+--------+

范围查询

使用in子查询:表示该操作数(字段值)等于该子查询的任意一个值就满足条件

返回所有以小开头的商品id

代码语言:javascript
复制
select pid from product where pid in
(select pid from product where pname like '小%');

返回以小开头的商品

代码语言:javascript
复制
select * from product where pid=any
(select pid from product where pname like '小%');

all

表示该操作数的值必须跟列子查询的所有值都满足给定的比较运算,才算满足了条件

返回商品最高的哪个商品

exists

如果该子查询有结果数据(无论什么数据,只要大于等于1行),则为true,否则为false

代码语言:javascript
复制
select * from product where exists
(select pid from product where pname like 'p%');
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/03/08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 连接
    • inner join(内连接)
      • left join(左连接)
        • full join (全连接)
        • 自关联
        • 内置函数
        • 子查询
          • 普通查询
            • 比较查询
              • 范围查询
                • all
                  • exists
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档