Heim  >  Artikel  >  Datenbank  >  MySQL中的基本查询语句学习笔记_MySQL

MySQL中的基本查询语句学习笔记_MySQL

PHP中文网
PHP中文网Original
2016-05-27 13:44:291177Durchsuche

MySQL中的基本查询语句学习笔记_MySQL

1.基本查询语句
select 属性列表 from 表名和视图列表 [where 条件表达式1] [group by 属性名1 [having 条件表达式2]] [order by 属性名2 [asc|desc]]
2.单表查询
1)使用*查询所有字段

select * from 表名;

2) 查询指定字段

select id,name from product;

使用上面例子可以查询指定字段

3)查询指定记录
where 条件表达式
实例:

select *from employee where id = 1002;

where 子句常用查询条件

比较:=、<、

[not] in (元素1,元素2,...,元素n)
实例:

select * from employee where id in (1001,1002);

如果集合中的元素为字符时,需加上单引号。

5)带between and 的范围查询
[not] between 取值1 and 取值2
取值1为起始值,取值2为终止值
实例:

select * from employee where age 
bewteen 15 and 20;

6)带like的字符串匹配查询
[not] like ‘字符串';
‘字符串'的值可以是完整的字符串,也可以是含百分号(%)或下滑线(_)的通配字符。

“% ”可以代表任意长度的字符串,长度可以是0。
“_”只能表示单个字符。
完整字符时like相当于“=”。
实例:

select * from employee where homeaddr like ‘北京%&#39;;

查询所有homeaddr字段中以“北京”
开头的记录。

select * from employee where name like "ar_c";

查询所有name字段值长度为4,前两个字母为“ar”最后一个字母为“c”的记录。
统配的字符串可以用单引号或双引号。
通配符“”可以多次使用,如“赵 _”。

7)查询空置
is [not] null
实例:

select * from work where info is null;

查询work表info字段为空的记录。

8)and 和 or多条件查询
条件表达式1 and 条件表达式2 [...and 条件表达式n]
and 表示同时满足所有条件的记录会被查询出来,or表示只要满足其中一条的记录就会被查询出来。

9)查询结果不重复
select distinct 属性名
实例:

select distinct age department_id employee;

10) 查询结果排序
order by 属性名 [asc|desc]
默认asc排序。
如果遇到某个字段存在空值的记录,需要注意,空值排序时可以理解为该字段的最小值。
mysql中可以指定按多字段排序。
实例:

select * from employee order by id asc , age desc;


3.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码进行计算的。

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

select 语句1 union|union all
select 语句2 union|union all...
select 语句n;
PS:为表或字段起别名
表起别名语法:

表名 表的别名

select * from department d where d.d_id =1001;

字段起别名语法:

属性名 [as] 别名
as可有可无。

select d_id as department_id,d_name as department_name from department;


以上就是MySQL中的基本查询语句学习笔记_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn