select用法

select 去重选项 字段列表 [as 字段别名] from 数据源 [where 子句] [group by 子句] [having子句] [order by 子句] [limit 子句]

1、select distinct * from student 查询学生表中的所有字段,并去重  去重针对的是查询出来的字段,而不是存储在表中的记录

2、seletct name as “姓名”,gender as “性别” from student  从student表中查询出name,gender字段,分别命名为姓名、性别

3、数据源可以是单表、也可以是多表,也可以是查询语句。

数据源是多表时,是将表中的x条记录与另一个表中的y条记录组成结果,记录数为x*y,俗称笛卡尔集

多表查询时:如何有效去除笛卡尔集的冗余呢

select * from student1 as s1,student2 as s2 where s1.id=s2.id

数据源是查询语句时,必须将查询语句起一个别名 如 select name from (seletc * from student )as d

4、where子句

  • 基于值:= <= like   

  where name=“lilei”   

  where age <= 24     

  where name like "li%"

  • 基于值的范围:in   not in  between x and y  [x,y]闭区间 

 where age in (28,29,30)年龄为28 29 30

where age not in(28,29,30) 年龄不为28 29 30

where age between 28 and 30 年龄在28到30之间,包括28和30

  • 条件复合:or  and not

where 条件1 or 条件2

where 条件1 and 条件2

where not 条件1

5、group by子句 将查询结果依据字段来分组

实际上,group by的作用主要是统计(某人的总分数,学生中女性的数量等),所以一般会配合一些统计函数来使用

count(x)统计x字段的记录数

max(x)

min(x)

avg(x)

sum(x)

6、having子句

having与where类似,不过having的条件判断发生在数据的内存中时,所以可以使用在内存中才发生的数据,如“分组”、“字段别名”等

select name as n,gender from student having n=“lilei”;

select name,gender,count(*)as “组员” from student as d group by name,gender having count(*)> 2;这里只显示记录数大于2的分组

7、order by +字段+[desc|asc]默认值asc

order by age desc 年龄降序排序

order by age asc,name desc age 字段升序,name字段降序

8、limit子句

当查询结果太多时,可使用limit限制结果的行数,limit x,y 其中x代表第一行数据的偏移量,y代表数据总量

limit 5,10 显示5-14条数据

limit 5,-1 显示5-last

limit 5 显示前5条数据,相当于limit 0,5

9、实践

查询工资最高人的信息,聚合函数不能用在where子句中

select * from erp where salary=(select max(salary)from erp)

或者 select * from erp where exists (select max(salary)from erp)

子查询出现在whre后是作为条件出现的

子查询出现在from之后是作为表存在的,作为表存在需要起一个别名

查询sxy的工作、工号、工资,

select job,deptno,sal from erp whre name=“sxy”

select * from emp where(job,deptno,sal)IN(select job,deptno,sal from emp where ename='殷天正');(查询和殷天正一样工作,工号,工资的人的工作,工号,工资从emp表中)

原文地址:https://www.cnblogs.com/xysun/p/12124907.html