MySQL系列2—查询语句详解

数据库查询

  1. 基本语法

    格式:select * from 表名;

    说明:select 后跟要查询的内容(字段名),*代表查询全部,from代表数据来源于哪张表

    示例:select name,id from student;

  2. 消除重复行

    在select跟字段之间使用distinct可以消除重复的行。

    示例:select distinct name from student;

  3. 条件查询

    a、语法:select * from 表名 where 条件;

    b、比较运算符:+,-,*,、,=,!=,<,>,%

    ​ 示例:select * from 表名 where id<18;

    c、逻辑运算符

    ​ and 并且 select * from student where id>7 and gender=0;

    ​ or 或者 select * from student where id>7 or gender=0;

    ​ 说明:只要满足任意条件都会匹配出来

    ​ not 不是 select * from student where id>7 not gender;

    d、模糊查询

    ​ 示例:select * from student where name llike ‘%a%’;(只要包含a就会匹配出来)

    ​ 说明:%代表包括空白在内的任意字符,_代表一个字符

    e、范围查询

    ​ in 在 select * from student where id in (1,3,4);

    ​ not in 不在 select * from student where id not in (1,3,4);

    ​ between and select * from student where id between 6 and 8;

    f、空判断

    ​ insert into student(name,age) values(‘小明’,70);

    ​ 说明:null 与’'不同

    ​ select * from student where address is null;(或者is not)

    g、优先级

    ​ 小括号,not 比较运算符,逻辑运算符

    ​ and 比 or 优先级高,如果同时出现并希望先选or,需要结合()使用

  4. 聚合查询

    a、count(*) 表示计算总行数,括号中可以写**和字段

    b、max(字段) 表示求此列的最大值

    c、min(字段) 表示求此列的最小值

    d、sum(字段) 表示求此列的和

    e、avg(字段) 表示求此列的和

    select max(age) from student where gender=‘0’;

  5. 分组查询

    按照字段分组,表示此字段相同的数据会被放到一个集合中。

    分组后,只能查询相同的数据列,对于有差异的数据列无法显示在结果集中,可以对分组数据进行统计,做聚合运算。

    语法:select 列1,列2,聚合…… from 表 group by 列1,列2,……

    示例:查询男女生总数

    select gender,count(*) from student group by gender;

    分组后的数据筛选:

    select 列1,列2,聚合…… from 表 group by having 列1,列2,……,聚合…… having 条件

    示例:select gender,count(*) from student group by gender having gender=0;

    where和having的区别:

    where是对from后面指定的表进行筛选,属于对原始表的筛选

    having是对group by的结果进行筛选

    示例:select id,name from teachers where name in (select name from teachers group by names having count(name)>1);

  6. 排序

    语法:select * from 表名 order by 列1 asc| desc,列2 asc|desc;

    说明:将数据按照列1进行排序,如果某些列1的值相同,那么按照列2排序

    ​ 默认按照升序排列,asc降序,desc降序

  7. 分页

    语法:select * from 表名 limit x,y;

    说明:从第x+1行开始,查询y行内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值