计算机网络/计算机科学与应用/系统/运维/开发

MySQL8 select查询

1、select简单查询 

1.1、无表查询:

mysql> select now() from dual;

+---------------------+

| now()               |

+---------------------+

| 2024-10-31 10:48:13 |

+---------------------+

1 row in set (0.00 sec)

mysql> select now();

+---------------------+

| now()               |

+---------------------+

| 2024-10-31 10:48:18 |

+---------------------+

1 row in set (0.00 sec)

dual表可以理解为一张虚拟的表或者可以省略

1.2、指定列查询

select * from sys_user;

select id,username from sys_user;

1.3、limit指定行和分页查询

select * from tab1  limit 5,10;

5,表示偏移量

10,表示数据量

2、where条件查询

2.1、单值查询

select * from sys_user where username= 'helen';

比较符:

>(大于)、<(小于)、!=或者<>(不等于)、>=(大于或等于),以及<=(小于或等于)

select * from sys_user where age >= 86;

<> 和 != 含义:

查询用户名称 不等于 Dara的所有用户

select * from sys_user where username != 'Dara';

等同于

select * from sys_user where username <> 'Dara';

一般推荐使用<>

2.2、between and 范围和区间查询 (包含边界值)

-- 查询所有0-7岁的儿童

select * from sys_user where age  between 0 and 7;

in 表示在一个非连续范围内的值

-- 查询所有3岁 7岁 18岁的用户

select * from sys_user where age in(3,7,18);

-- 查询名字叫Yvonne Chloe Maite用户

select * from sys_user where username('Yvonne','Chloe','Maite');

查询不在范围区间 ,在between..and .. 以及in前面加not表示

select * from sys_user where age not between 0 and 7;

select * from sys_user where age not in(3,7,9);

3、like模糊查询

使用MySQL提供的模糊查询关键字like

%表示匹配任意数量的字符,甚至零个字符

_ 表示匹配任意一个字符

-- 查询姓名以A开头的用户

select * from sys_user where username like 'A%';

-- 查询小龙开头的数据  第3个字可以存在,也可以不存在 比如 小龙 小龙女

select * from sys_user where username like '小龙%';

% 和 _ 可以放在查询值的任何地方,并且可以是任意数量%和_

select * from sys_user where username like '小%女';

select * from sys_user where username like '小_女';

select * from sys_user where username like '__女';

4、空值查询

创建表时可以指定字段是否必填,对于非必填的字段,如果该字段不存在值,则称之为包含空值null

MySQL 判断是否为null 方法有 is null 和 is not null 

-- 查询邮箱为null的用户

select * from sys_user where email is null;

-- 查询邮箱不为null的用户

select * from sys_user where email is not null;

null不等于空字符('')

-- 查询邮箱为''的用户

select * from sys_user where email = '';

select * from sys_user where email !='';

注意: 

空字符串使用比较运算符时,建议使用 = 或者 != 

null 使用is null 或者 is not null 

空字符串不占用空间  null占用空间 

空字符串('')的长度是0,不占用空间;null的长度是null,占用空间。

使用count()统计某列的记录数时,如果采用的是null,则会被系统自动忽略掉;

如果采用的是空字符串,则会被统计

5、where多值查询

and 和 or 组合查询 

and 并且  or或者的意思

select * from sys_user where username = '小龙女' and  age = 18;

6、数据排序 order by 

-- 按年龄从小到大排序 升序

select * from sys_user order by age asc;  --asc默认 升序 也可以省略

select * from sys_user order by age;

-- 降序

select * from sys_user order by age desc;

-- 多列排序 先按第一个值排序 在进行第二个值排序

select * from sys_user order by age asc,username desc;

7、数据分组group by

group by 分组 分组后对每组数据进行函数运算(sum max avg count)

group by 支持多字段分组

8、分组后过滤having

group by可以对数据进行分组,如果想对分组的数据进行过滤,则需要使用having子句

having子句是分组后过滤的条件,在group by之后使用,也就是说如果要用having子句,则必须先有group by子句。

select student_id,avg(score) as '平均成绩'

from student_score 

group by student_id;


你努力了什么,也就成就了什么,与其羡慕别人,不如蜕变自己。

评论

^