Mysql 入门,增删改查(进阶篇)
Posted Syw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql 入门,增删改查(进阶篇)相关的知识,希望对你有一定的参考价值。
SELECT查询组合使用的关键字很多,首先将最简单常用的关键字进行区分及使用,后续再继续补充............
以下所有的关键字组合使用,主要以两个表students与students_score为主,进行练习,
(1)join:主要分为以下几种
join:
inner join(内连接或等值连接):取出两个表中存在连接匹配的记录表
right join(右连接):取得右表的全部记录,已右表为准
left join(左连接): 与right join相反
说明:1、mysql不支持Full join
2、已左连接为主,如果左表中的数据右表中也存在,则以左表为主显示数据, 2、已右连接为主,如果右表中的数据,左表中无,则以null填充
1) select sc.name,sc.math_score,s.name from students_score sc INNER JOIN students s on s.id = sc.id ;
2)select sc.name,sc.math_score,s.name from students_score sc JOIN students s on s.id = sc.id ;
3)select sc.name,sc.math_score,s.name from students_score sc left JOIN students s on s.id = sc.id ;
4)select sc.name,sc.math_score,s.name from students_score sc right JOIN students s on s.id = sc.id ;
5)(select sc.name from students_score sc right JOIN students s on s.id = sc.id) union (select s.name from students s left JOIN students_score sc on s.id = sc.id ); #
(2)limit: 强制select语句返回指定的记录数,支持1个或者2个数字(必为正整数)参数
SELECT * FROM students LIMIT 3,3; #第一个数字代表着从第几个开始(如:3,代表着从3开始,但是不包含3),第二个数字代表着显示几个
SELECT * FROM students LIMIT 1; #返回一条记录
示例:select id,tel from students where tel = \'18392868125\' limit 1; #拉出一条tel为18392868125的数据
(3)group by: 分组功能
SELECT sex as \'性别\',avg(age) as \'平均年龄\' FROM students group by sex ORDER BY age desc; #根据性别显示平均年龄,并且按降序排列
对表students做的分组查询,运行结果显示如下:
(4)order by:排序
通过某些字段进行排序,order by后面跟上排序字段,可以跟多个字段,每个字段之间用逗号隔开,如果语句中有where子句,则order by必须放在where后,order by默认的排序是升序(ASC),降序使用(DESC)
select id,math_score from students_score ORDER BY math_score desc; #降序排列,默认升序,如需添加升序则用关键字“ASC”
(5)in: 允许在where字句中规定多个值
select * FROM students where id in(2,3,5,6); #取出ID为2,3,5,6的所有信息
(6)between....and......:取出某一区间的值
select * from students where id between 4 and 6;
in 与 between....and......的区别:in后面跟的是集合,between后面跟的是一个区间
(7)not: 不在什么中
select * from students where id not in(1,2,3,4);
(8)distinct :去掉重复的数值
select distinct tel from students; #拉出tel列去重数据,拉出tel列电话号码不重的数据
(9)union,连接两个表的查询结果
union all: union:会去掉重复的行。union all不去掉重复的行
(select id,math_score from students_score) UNION (select id,english_score from students_score);
(select id,math_score from students_score) UNION all (select id,english_score from students_score);
以上是关于Mysql 入门,增删改查(进阶篇)的主要内容,如果未能解决你的问题,请参考以下文章