Mysql查询语句汇总

一、单表查询

1、全表数据查询

语法格式:select * from 表名;
例:select * from students;

2、查询指定字段

语法格式:select 字段1,字段2 from 表名;
例:select name,age from students;

3、带where表达式的查询

语法格式:select 字段名 from 表名 where 条件表达式;
例:select name from students where score = 98;
select name from students where score>=80;

4、带in关键字查询

语法格式:select 字段名 from 表名 where 字段 [not]in(元素1,元素2);
例:select name from students where score in(60,70);

5、带between and的范围查询

语法格式:select 字段名 from 表名 where 字段 [not]between 取值 and 取值1;
例:select name from student where age between 20 and 25;

6、带like的模糊查询

'%'代表任意字符;
'_'代表单个字符;

select 字段名 from 表名 where 字段名 like’字符串’;
例:select score from student where name like’%张%';匹配含有张的所有字符

7、空值查询

select 字段1,字段2… from students where 字段 is [not] null

8、带and、or的多条件查询

语法格式:select 字段1,字段2 from 表名 where 条件1 and 条件2;
select 字段1,字段2 from 表名 where 条件1 or 条件2;
例:select name score from students where grade=‘计算机’ and age=24;
select name score from students where grade=‘计算机’ or age=24;满足一个条件执行

9、去重查询(distinct)

语法格式:select distinct 字段名 from 表名;

10、对查询结果排序

语法格式:select 字段1,字段2… from students order by 属性名 [desc|asc];
例:select * from student order by age desc;
注:desc从大到小排序,asc从小到大排序(默认排序方式)

11、分组查询(group by)

语法格式:group by 属性名 [having 条件表达式][with rollup]

1、与group_concat()函数一起使用

select class,GROUP_CONCAT(name) from students.users GROUP BY class;

image.png

2、与聚合函数一起使用

select class,COUNT(name) from students.users GROUP BY class;

image.png

12、limit分页查询

语法格式:select * from 表名 limit 起始值,记录数;
select * from students.users limit 2,7;

二、多表查询

1、左连接(LEFT JOIN)

select 字段列表
from A表 left join B表
on 关联条件
例:select stu_users.sno,stu_users.sname,sc.score from stu_users
LEFT JOIN sc on stu_users.sno=sc.sno;

2、右链接

select 字段列表
from A表 right join B表
on 关联条件

3、联合查询

select 语句1
union[union 选项]
select 语句2
union|[union 选项]
select 语句n
注:其中union选项有两个选项可选
all:表示无论重复都输出
distinct: 去重(整个重复)(默认的)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@不会写代码的小张

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值