MySQL语句简介(三)查询语句以及外键......

在前段时间的学习中涉及到了一点SQL语句,于是在学习过后记录一下,方便以后查找使用
:::我使用的是Navicat for MySQL(由于时间匆忙,语句后的标点都省略了)(还有大小写问题,因为在Navicat for MySQL中大小写都是可以的,所有在此处全部用小写来表示)
由于外键的设置以及一些“高级查询”(至少现在的我还认为是比较”高端“的查询)是之后又新学的,所以就都全部加到第三篇中来了

查询
一普通查询
1、查看表的细节(这个好像不是很常用,我也没试过)

show create table student;

2、查询所有数据

select * from student(取出表的所有数据)

3、查询一行的数据

select*from student where id =1;只查询id=1的行

4、模糊查询(_代表一个字母,%代表多个字母)

select * from students where name like '_____'(查询名字有五个字母的人

5、去重操作(如果查询出来的数据有重复的话便只显示一条)

select distinct name from students;

6、对字段的结果经行运算(但必须是整数型)

select * ,age+score from students;
select *, ifnull(age,1)+ifnull(score,1) as total from students;
//如果指针遇到空的地方就把它变成1,之后再展示

7、合并结果集
就是把多个查询同时显示在一张表中,关键字使union,而且合并是会默认去除重复的记录,但是如果使用union all 的话则不会去除重复记录
注意:合并的两个表的所要查询的结果的列数以及列类型必须相同
eg:

select * from 表1 union select *from 表2;
select * from 表1 union all select *from 表2;

二,函数类(MAX,MIN…)
1、查询表中的数量
select count(*) from student;
统计表中有绩效的人数:
select count(performance) from student
count是统计不为null的数量
查询成绩大于100的人数
select count(*) from employ where slary>100;
2、查询数据和(这个不是求和查询)

select sum(salary),sum(performance) from employee;

3、求两列的和:
select sun(salar+performance) from employee;
4、平均:
select avg(salary) from emoloyee;
5、最大:
select max(salary) from employee;
6、最小:
select min(salary) from employee;
将5、6合起来查询:
select max(salary),min(salary) from employee;
三、分组查询
group by(单独使用的时候只会显示每一组的第一条记录)

select * from employee group by gender;

这有两个例子,将名字也一起显示出来加入了(group_concat)

select department,group_concat('name') from employee group by department;
select gender ,group_concat('name') from employee group by gender;

group_concat是将内容也显示出来的
(此处有些简略,这的笔记忘记保存了,只能按照记忆)
四、分组查询+聚合函数

select department,group_concat(salary),sum(salary) from employee group by department;
//这一条就比较简单了,应该可以自行看懂

此处得说一下having和where的区别
where后面不能使用聚合函数,having 后面可以使用聚合函数
having : 在分组前对数据进行过滤
where :在分组前对数据进行过滤

一个例子:

select department,sum(salary) from employee
where aslary>2000
group by department 
having sum(saraly)>6000 
order by sum(salary) desc;  //这一行是对数据进行降序排序

书写的顺序一般是:
from–where–group by–having–select–order by–limit
五、外键
因为在实际的项目中表和表之间不可能都没有联系,这就导致了外键的出现
如果想给两个表添加外键的话,两个表都必须使是 InnoDB 类型的
六、跨越多个表的查询(要把主键和外键保持一致)

1九九查询:
eg:

select * from student stu,score sc where stu.id=sc.sid;

或者是三个表中的查询:

select st.'name',sc.score,c.name 
from stu st,score sc,course c 
where st.id=sc.sid and sc.cid =c.cid;

2内连接
(等值连接)
select * from stu st inner join score sc ON st.id = sc.sid;
3、外连接
左链接,也叫左外连接

select * from stu st left  (outer) join score sc on st.id=sc.sid;

即 把左边表里的全部显示出来,右边的只显示满足条件的数据


右连接

select * from stu st right (outer) join score sc on st.id=sc.sid;

即 把右边表里的全部显示出来,左边的只显示满足条件的数据

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值