Chapter3 MySQL的查操作汇总
文章目录
Chapter3 MySQL的查操作汇总一、基本查询语句二、进阶查询语句三、连表操作四、数据行的其他操作
一、基本查询语句
select * from tb1
;
select id
,name
from tb1
;
select id
,name
from tb1
where id
>10 or name
='xxx';
select id
,name
as cname
from tb1
where id
>10 or name
='xxx';
select name
,age
,11 from tb1
;
二、进阶查询语句
1.大于、小于、不等于
select * from tb1
where id
!=1;
select * from tb1
where id
<>1;
2.选择、区间
select * from tb1
where id
in (1,5,12);
select * from tb1
where id
= 1 or 5 or 12;
select * from tb1
where id
not in (1,5,12);
select * from tb1
where id
between 5 and 12;
select * from tb1
where id
in (select id
from tb2
);
3.通配符
select * from tb1
where name
like "a%";
select * from tb1
where name
like "a_";
select * from tb1
where name
like "%a%";
4.分页
select * from tb1
limit 10;
select * from tb1
limit 0,10;
select * from tb1
limit 10 offset 20;
5.排序
select * from tb1
order by id
desc;
select * from tb1
order by id
asc;
select * from tb1
order by age
desc,id
desc;
select * from tb1
order by id
desc limit 10;
6.分组
分组常用的函数有:count
,max
,min
,sum
,avg
select count(id
),max(id
),part_id
from userinfo
group by part_id
;
注:对于聚合函数结果进行二次筛选时,条件
where应改为
having,如下
select count(id
),part_id
from userinfo
where id
>0 group by part_id
having count(id
)>1;
注:进行多次筛选时,先
where再
group by再
having
三、连表操作
1.左右连表
select * from userinfo
,department
;
select * from userinfo
,department
where userinfo
.part_id
=department
.id
;
select * from userinfo
left join department
on userinfo
.part_id
=department
.id
;
select * from userinfo
right join department
on userinfo
.part_id
=department
.id
;
select * from userinfo
inner join department
on userinfo
.part_id
=department
.id
;
注:当左右连接时,假如有
NULL值时
A
left join B AB且A完全显示 (
left join的左边完全显示)
B
left join A BA且B完全显示
A
right join B AB且B完全显示 (
right join的右边完全显示)
B
right join A BA且A完全显示
注:连表时,两张表若出现列明重复可能出错,因为连表结果中的重复列后期可能无法选中,所以
select xxx与
on xxx应带上表名。另外,当有连续的
left join/right join时,下面的语句可以引用上面的语句已经连好的表。比如student表中原来没有class列,连表后有了,则可以在后面的
left join中提到student
.class。
2.上下连表
select id
,name
from tb1
union
select num
,sname
from tb2
select sid
,sname
from student
union all
select sid
,sname
from student
四、数据行的其他操作
1.临时表
(select * from tb1
where id
>10)
2.指定映射
select id
,name
,1,sum(x
)/count()
3.条件
case when id?
8 then xx
else xx
end
4.三元运算
if(isnull
(xx
),0,1)