Mysql数据库中有哪些常用的sql语句?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

SQL语句进阶

1.查询字段:

————查询所有字段

select*from表名;

————查询指定字段

select字段名,字段名…from表名;

————多数据表连接查询时

select表名.字段名,表名.字段名…from表名;

————使用as给表起别名

select表别名.字段名from表名as表别名;

————消除重复行(distinct)

selectdistinct字段名from表名;

2.条件查询:

————比较运算符(>,<,=,!=)

select*from表名whereage>18;

(<>也表示!=)

————逻辑运算符(and,or,not)

select*from表名whereage>18andage<28;(18

3.排序:

————升序

select*from表名orderbyasc;(默认为升需asc,可以省略asc)

————降序

select*from表名orderbydesc;

4.聚合函数:

————总数count

selectcount(*)from表名;

————最大值max

selectmax(age)from表名;

————最小值min

selectmin(age)from表名;

————求和sum

selectsum(age)from表名;

————求平均值avg

selectavg(age)from表名;

————四舍五入保留小数round

selectround(avg(age),2)from表名;(查询平均年龄,四舍五入保留两位小数)

5.分组(重点):

————分组group by

selectgendercount(*)from表名groupbygender;(按性别分组,查询性别与人数)

————分组查询(聚合函数,group_concat(),having)

selectgenderavg(age)from表名groupbygender;(查询每种性别的平均年龄)selectgendergroup_concat(name)from表名groupbygender;(group_concat(name)查看分组姓名)selectgendercount()from表名groupbygenderhavingcount()>2(having类似where,过滤条件,having只能用于groupby,where用于表数据)

————汇总with rollup

selectgendercount(*)from表名groupbygenderwithrollup;(最后新增一行,显示汇总结果)

6.分页:

————查询前n个数据(limit一般写在最好,表示对操作后的数据显示)

select*from表名limitn;

————分页显示

select*from表名limit0,3;(每页显示3个,第1个页面)select*from表名limit3,3;(每页显示3个,第2个页面)select*from表名limit6,3;(每页显示3个,第3个页面)

7.连接查询(重点):

————inner join…on(内连接)

select*from表名1innerjoin表名2on表名1.cls_id=表名2.id;(将表1cls.id和表2id相同的连接在一起)select表名1.字段名1,表名2.字段名.2from表名1innerjion表明2on条件;

————left/right join…on(左/右/外连接)

select*from表名1left/rightjoin表名2on表名1.cls_id=表名2.id;(查询的结果为两个表匹配到的数据和左表特有的数据,对于左/右表中不存在的数据使用null填充)

8.子查询:

————标量子查询(子查询返回的结果是一个数据(一行一列))

select*from表名whereage>(selectavg(age)from表名);

————列子查询(返回的结果是一列(一列多行))

selectnamefrom表名1whereidin(selectcls_idfrom表名2);

————行子查询(返回的结果是一行(一行多列))

select*from表名where(height,age)=(selectmax(height),max(age)from表名);

看完上述内容,你们掌握Mysql数据库中有哪些常用的sql语句的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!