先准备两张表:
tb1
tb2
1.查询所有字段
select * from tb1;
2.查询指定的列
select id from tb1;
3.给表取别名
select id from tb1 t1; 或者 select id from tb1 as t1;
4.给列取别名
select id as ip from tb2 as t1 where t1.id=1;
在sql语句里面要t1.id获取id这一列,但是在结果集里要用ip获取id这一列,这个后面写MyBatis博客的时候会再说明。
5.查询指定记录
select * from tb2 where age>16;
where 里面支持 < > <= >= != and or 定义优先级的时候可以用夸号
如:select * from tb2 where (age>1 and age <16) or age=66;
5.使用in关键字 以及not关键字
select * from tb1 where age in(1,2,3);
select * from tb1 where age not in(1,2,3);
in 里面也可以是另一个select语句的结果集
6.使用like关键字
% 匹配任意多个字符(包括空字符) _ 匹配任意一个字符(不包括空字符)
select * from tb1 where name like '%a' or name like '_a';
7.查询空值 is null 查询非空值 is not null
select name from tb1 where name is not null;
8.查询结果集去重
select distinct * from tb1;
9.对结果集进行排序
select * from tb1 order by id; 按id列从小到大排序;
select * from tb1 order by id desc; 按id列从小到大排序;
也可以指定多个字段排序
select * from tb1 order by id desc,name; 按id降序 如有相同按name升序
10.分组查询(如果有排序,只能先分组再对分组进行排序,语句的顺序如下where group by having order by limit)
select * from tb1 group by id order by name;
11.分组查询的having子句
select * from tb1 group by id having name like '%a' order by name desc;
分组之后每组只能出现一行记录,也可以多字段分组
12.使用limit限制查询结果数量
select * from tb1 limit 3; 查询前三条
select * from tb1 limit 1,3; 偏移一行,再取之后的三条
13.聚集函数
avg() 返回某列的平均值
count() 返回某列的行数
max() 返回某列的最大值
min() 返回某列最小值
sum() 返回某列值之和
14.连接查询
select * from tb1 join tb2; 笛卡尔积
select * from tb1 join tb2 on tb1.id = tb2.id; 消除笛卡尔积
最后再详说7种连接情况
15.any和some关键字
两个关键字作用一样,只要满足结果集里任意一条即可
select * from tb1 join tb2 on tb1.id=tb2.id where age> any (select age from tb2);
16.all关键字
和上面的any和some相反,必须满足结果集里全部的
select * from tb1 join tb2 on tb1.id=tb2.id where age>= all (select age from tb2);
17.exists 和 not exists关键字
select * from tb1 where exists (select * from tb2 where age>10);
只有结果集存在就返回true
18.合并查询结果union (去重) union all (不去重)
select * from tb1
union all
select * from tb1;
19.七种join连接(使用mysql5.5)
重新准备表tb1和tb2
假设左边的圆表示tb1 右边的圆表示tb2 他们共有的id部分表示B
1.表示A区域
2.表示B区域
3.表示C区域
4.表示AB区域
5.表示BC区域
6.表示AC区域 = A+C
7.表示ABC区域
详细的用例可以去查相关书籍,后面出一篇博客MySQL查询练习题。