网站建设需要会一些啥,山西网络营销方案,厦门网站建设格,头像制作在线生成器使用数据库最终要的莫过于查询数据#xff0c;所以这里将会详细的介绍mysql数据库中查询语句的使用
普通查询
使用基本的select关键字进行查询#xff0c;其语法及使用如下
# 格式
select [select选项] 字段 [as 别名] from 数据表;# 查询出所有字段的值#xff0c;不建议…使用数据库最终要的莫过于查询数据所以这里将会详细的介绍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 5group by用于引导分组查询语句group by agehaving作用类似于where但是它是对内存中的数据进行过滤通常和group by连用可以使用字段的别名进行条件判断group by age having count(age) 5order by排序查询对查询出的数据进行排序asc表示升序desc表示降序order by id desclimit用于限制返回查询的数据记录数一般用于分页使用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;# ab 匹配b之前出现过a的记录至少1次
select id,name,age from user where name regexp ls;# 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};