Mysql数据库之常用sql语句进阶与总结

2022-05-22 0 636

本文实例讲述了Mysql数据库之常用sql语句。分享给大家供大家参考,具体如下:

前面讲述了Mysql sql基本语句。这里继续总结一下SQL语句的进阶内容。

SQL语句进阶

1.查询字段:

————查询所有字段

select * from 表名;

————查询指定字段

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

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

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

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

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

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

select distinct 字段名 from 表名;

2.条件查询:

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

select * from 表名 where age >18; 

(<>也表示!=)

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

select * from 表名 where age>18 and age<28;(18

3.排序:

————升序 

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

————降序

select * from 表名 order by desc;

4.聚合函数:

————总数count

select count(*) from 表名;

————最大值max

select max(age) from 表名;

————最小值min

select min(age) from 表名;

————求和sum

select sum(age) from 表名;

————求平均值avg

select avg(age) from 表名;

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

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

5.分组(重点):

————分组group by

select gender count(*) from 表名 group by gender;(按性别分组,查询性别与人数)

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

select gender avg(age) from 表名 group by gender;(查询每种性别的平均年龄)

select gender group_concat(name) from 表名 group by gender;(group_concat(name)查看分组姓名)

select gender count() from 表名 group by gender having count()>2(having类似where,过滤条件,having只能用于group by,where用于表数据)

————汇总with rollup

select gender count(*) from 表名 group by gender with rollup;(最后新增一行,显示汇总结果)

6.分页:

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

select * from 表名 limit n;

————分页显示

select * from 表名 limit 0,3;(每页显示3个,第1个页面) 
select * from 表名 limit 3,3;(每页显示3个,第2个页面) 
select * from 表名 limit 6,3;(每页显示3个,第3个页面)

7.连接查询(重点):

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

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

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

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

8.子查询:

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

select * from 表名 where age > (select avg(age) from 表名);

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

select name from 表名1 where id in (select cls_id from 表名2);

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

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

更多关于MySQL相关内容感兴趣的读者可查看本站专题

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 MySql Mysql数据库之常用sql语句进阶与总结 https://www.niceym.com/44684.html