MySQL中有哪些数据查询语句

来源:这里教程网 时间:2026-02-28 16:07:49 作者:

一、基本概念(查询语句)

①基本语句

②条件查询

1)比较运算符:>, =,

2)逻辑运算符:and, or, not

3)模糊查询:like, rlike

4)范围查询:in,not in,between…and,not between…and

空判断

排序:order_by

分组:group_by, group_concat():查询内容, having

分页: limit

limit start,count   (start:表示从哪─个开始;count:表示数量)
即limit(第N页-1)*每个的个数,每页的个数;
limit在使用的时候,要放在最后面.

5)聚合函数:count(), max(), min(), sum(), avg(), round()

6)连接查询 :inner join, left join, right join

left join是按照左边的表为基准和右边的表进行查询,查到就显示,查不到就显示为null

补充

注意:WHERE子句中是不能用聚集函数作为条件表达式的!

二、总结

1、普通查询

(1)命令:select * from ;

(2)命令:select from ;

2、去重查询(distinct)

命令:select distinct from

3、排序查询(order by)

升序:asc

降序:desc

降序排列命令:select from order by desc

不加desc一般默认为升序排列

4、分组查询(group by)

命令:select , Sum(score) from group by

假设现在又有一个学生成绩表(result)。要求查询一个学生的总成绩。我们根据学号将他们分为了不同的组。

命令:

select id, Sum(score) 
from result 
group by id;

现在有两个表学生表(stu)和成绩表(result)。

5.等值查询

当连接运算符为“=”时,为等值连接查询。

现在要查询年龄小于20岁学生的不及格成绩。

select stu.id,score 
from stu,result 
where stu.id = result.id and age < 20 and score < 60;

等值查询效率太低

6.外连接查询

①语法

select f1,f2,f3,....
from table1 left/right outer join table2
on 条件;

②左外连接查询,例如

select a.id,score
from
  (select id,age from stu where age < 20) a (过滤左表信息)
left join
  (select id, score from result where score < 60) b (过滤右表信息)
on a.id = b.id;

左外连接就是左表过滤的结果必须全部存在。右表中如果没有与左表过滤出来的数据匹配的记录,那么就会出现NULL值

③右外连接查询,例如

select a.id,score
from
  (select id,age from stu where age < 20) a (过滤左表信息)
right join
  (select id, score from result where score < 60) b (过滤右表信息)
on a.id = b.id;

右外连接就是左表过滤的结果必须全部存在

7.内连接查询

①语法

select f1,f2,f3,....
from table1 inter join table2
on 条件;

②例如

select a.id,score
from
  (select id,age from stu where age < 20) a (过滤左表信息)
inner join
  (select id, score from result where score < 60) b (过滤右表信息)
on a.id = b.id;

8.合并查询

在图书表(t_book)和图书类别表(t_bookType)中

①.union

使用union关键字是,数据库系统会将所有的查询结果合并到一起,然后去掉相同的记录;

select id 
from t_book  
 union 
select id 
from t_bookType;

②.union all

使用union all,不会去除掉重复的记录;

select id 
from t_book  
 union all 
select id 
from t_bookType;

相关推荐