mysql数据库

mysql-查询3

2015-11-22  本文已影响95人  GALAXY_ZMY
1.limit限制查询结果条数
1)不指定起始位置

limit 记录数

记录数超过查询结果则显示所有的记录,不会报错

2)指定起始位置

limit 起始位置 , 记录数

记录的起始位置从位置0开始。

2.使用集合函数查询

集合函数包括count(),sum(),avg(),max()和min()。

1)count()函数

统计记录条数
实例:
select count(*) from employee;
与group by一起使用
select d_id,count(*) from employee group by d_id;
上述语句会先分组后统计。

2) sum()函数

sum()函数是求和函数

实例:
select num,sum(score) from grade where num= 1001;

select num,sum(score) from grade group by num;

sum()只能计算数值类型字段。

3)avg()函数

avg()函数是求平均值函数。

实例:
select avg(age) from employee;

select course,avg(score) from group by course;

4)max(),min()函数

求最大值和最小值。
实例:
select max(age) from employee;
select num,course,max(score) from grade group by course;
对于字符串的最大值问题,max()函数是使用字符对应的ascii码进行计算的。

3.连接查询

将两个及两个以上的表连接起来选取所需数据。

1)内连接查询:

当两个表中具有相同意义的字段值相等时,就查询出该条记录。
实例:
select num,name,employee.d_id,age,d_name from employee,department where employee.d_id = department.d_id;
因字段名相同,所以取d_id字段值时最好指定哪张表的字段。

2)外连接查询

select 属性名列表 from 表名1 left|right join 表名2 on 表名1.属性名1=表名2.属性名2;

左连接查询:
进行左连接查询时,可以查出表名1中所指的表中所有记录。而表名2所指表中,只能查询出匹配的记录。
实例:
select num,name,employee.d_id,age,d_name from employee left join department on employee.d_id = department.d_id;
右连接查询:
与左连接相反,可以查询出表名2中的的所有记录,而表名1中所指的表中,只查询出匹配的记录。

4.合并查询结果

使用union和union all关键字。
union将查询的结果合并到一起并去掉形同的记录,union all 只是简单地合并到一起。

select 语句1 union|union all
select 语句2 union|union all...
select 语句n;

5.为表或字段起别名

表起别名语法:

表名 表的别名

select * from department d where d.d_id =1001;
字段起别名语法:

属性名 [as] 别名

as可有可无。
select d_id as department_id,d_name as department_name from department;

上一篇 下一篇

猜你喜欢

热点阅读