使用数据库最终要的莫过于查询数据,所以这里将会详细的介绍mysql数据库中查询语句的使用
普通查询
使用基本的select关键字进行查询,其语法及使用如下
# 格式
select [select选项] 字段 [as 别名] from 数据表;# 查询出所有字段的值,不建议直接写*
select * from user;# 查询出指定字段的值
select id,name from user;# 过滤掉指定字段重复的数据,自动过滤调用多余的id和name两个字段值相同的记录
select distinct id,name from user;# 给查询出的字段去别名
select name as user_name from user;
带有子句的查询
mysql中的子句有5类,如下:
where | 用于条件判断,过滤数据,判断条件有:> ,< , >= ,<= ,!= ,like ,between and ,in/not in ,and ,or 。 where是唯一一个直接从磁盘获取数据时就进行判断的条件 | where id = 5 |
group by | 用于引导分组查询语句 | group by age |
having | 作用类似于where,但是它是对内存中的数据进行过滤,通常和group by连用,可以使用字段的别名进行条件判断 | group by age having count(age) > 5 |
order by | 排序查询,对查询出的数据进行排序,asc表示升序,desc表示降序 | order by id desc |
limit | 用于限制返回查询的数据记录数,一般用于分页使用 | limit 10 |
以上几个子句可以混合使用,接下来写几个实例,来看一下如何使用
# 使用where进行条件判断
select name,age from user where id > 2;# 获取当前表中前10条数据
select name,age from user limit 10;# 获取表中第5到第8条数据
select name , age from user limit 4,4; # 获取表中第i到第j条数据
select name ,age from user limit (i-1) , (j-i-1) ;# 查询user表中有哪几类名字
select name from user group by name;# 将所有数据按着年龄大小排序(NULL值默认是最小的)
select name,age from user order by age desc;# 查询相同名字数量大于2的有几人,名字是什么(count是一个内置的函数,用于计算个数,有几条记录,count函数的值就为几)
select name ,count(name) from user group by name having count(name) > 2;
联合查询
联合查询指的是将多个查询结果组成一个查询结果返回,使用union关键字完成联合查询,注意每一个查询结果的返回字段数、类型必须一致,一般在处理多个类型不同但是数据结构相同的表时使用,实例如下:
# 联合查询,过滤掉所有对应字段值都相同的数据
select name,age from user1 where id < 5
union
select name,age from user2 where id > 7;# 联合查询,不会过滤掉所有对应字段值都相同的数据
select name,age from user1 where id < 5
union all
select name,age from user2 where id > 7;
正则查询
# ^匹配以特定字符串开头的记录
select id,name,age from user where name regexp '^li';# $匹配以特定字符串结尾的记录
select id,name,age from user where name regexp 'si$';# .匹配字符串的任意一个字符(只要带s的都会被查询到)
select id,name,age from user where name regexp '.s';# [字符集合] 匹配字符集合中的任意一个字符,只要name值带有i或者s的都会被查询到
select id,name,age from user where name regexp '[is]';# [^字符集合] 匹配除字符集合以外的任意一个字符
select id,name,age from user where name regexp '[^is]';# S1|S2|S3 匹配S1,S2,S3中的任意一个字符串
select id,name,age from user where name regexp 'si|san';# a*b 匹配b之前出现过a的记录,包括0次
select id,name,age from user where name regexp 'l*s';# a+b 匹配b之前出现过a的记录,至少1次
select id,name,age from user where name regexp 'l+s';# a{N} 匹配字符串a连续出现过N次的记录
select id,name,age from user where name regexp 'i{2}';# a{M,N} 匹配字符串至少出现过M次,至多出现过N次的记录
select id,name,age from user where name regexp 'i{2,5}';