MySQL statement test - data query

MySQL statement test - data query

3.4 数据查询
一、单表查询
/*1.选择表中的若干列,各个列的先后顺序和语句中列名从左到右的顺序一致
    select 目标表达式 from 表名;
*/
/*(1)select 列名 from 模式名.表名;*/
select Sno,Sname from zyl.student;
/*(2)若要查询全部列可用*代替*/
select * from student;
/*(3)查询经过计算的值(目标表达式:列名/表达式/字符串常量/函数等)*/
select Sname,2014-Sage from student;

select Sname,'Year of Birth:',2014-Sage,lower(Sdept) from student;
/*(4)指定别名来改变查询结果的标题
    select 列名/表达式/字符串常量/函数 别名 from 模式名.表名;
*/
select Sname,'Year of Birth:' birth,2014-Sage birthday,lower(Sdept) department from student;

/*2.选择表中的若干元组
    select all/distinct(默认为all) 列名/表达式/字符串常量/函数 from 模式名.表名;
*/
/*(1)消除取值重复的行*/
select Sdept from student;          /*此时有很多重复项*/

select distinct Sdept from student; /*distinct去掉了重复项*/
/*(2)查询满足条件的元组,可以通过where语句实现*/
/*①比较大小
=, >, <, >=, <=, !=, <>, !>, !<
*/
select sname,sage from student where Sage=20;
/*②确定范围,特指数据为数值型的
between... and... ,not between... and...
*/
select sname,sdept,sage from student where sage between 19 and 20;
/*③确定集合
in, not in
*/
select sname,sdept,sage from student where sdept in('CS');
/*④字符匹配
like, not like

%(百分号)表示任意长度的字符串
_(下横线)表示任意单个字符
*/
select sname,sdept,sage from student where sname like '张%';

/*所要查询的字符串本身有%或_时,不需要转义*/
insert into student(sno,sname,ssex,sage,sdept) values ('20162300','娄_java','男','40','IS');
select sno,sname from student where sname like '娄\_java';               /*运行成功*/
select sno,sname from student where sname like '娄\_java' escape '\';    /*报错*/
/*⑤涉及控制的查询
is null, is not null
*/
insert into student(sno,sname,ssex,sdept,sage) values ('20160000','','','','0');
select sno,sname,sdept,sage from student where sname is null;           /*此时并不能查到20160000*/

insert into student(sno,ssex,sdept,sage) values ('20160001','','','0');
select sno,sname,sdept,sage from student where sname is null;           /*此时能查到20160001,显示sname为null*/
/*⑥多重条件查询
and, or, not
*/
select sno,sname,sdept,sage from student where Sdept='CS' and Sage<20;

select sname,sdept,sage from student where sdept in('CS','43');
select sname,sdept,sage from student where sdept='CS' or sdept='43';
等价

/*3.order by子句,asc升序、desc降序*/

/*4.聚集函数
count :统计元组个数
count distinct/all 列名:统计一列中值的个数
sum distinct/all 列名:计算一列值的总和
avg distinct/all 列名:计算一列值的平均数
max distinct/all 列名:求一列值的最大值
min distinct/all 列名:求一列值的最小值
*/

/*5.group by子句
将查询结果按某一列或多列的值分组,值相等的为一组
select 列名/表达式/字符串常量/函数 from 表名 group by 列名 having 条件条件表达式;
where语句不能与group by连用,where子句中不能用聚集函数作为条件表达式,用having代替
*/

二、连接查询
三、嵌套查询
四、集合查询
五、基于派生表查询

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325514268&siteId=291194637