[[数据库]] MySQL的select(查)操作及其他操作汇总 MADPEACH

    科技2022-07-14  116

    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; #多了一列,值全为11

    二、进阶查询语句

    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_"; #后面只有1个字符 select * from tb1 where name like "%a%"; #有a就行 4.分页 select * from tb1 limit 10; #前10个 select * from tb1 limit 0,10; #从0开始,取10个 select * from tb1 limit 10 offset 20; #从20开始,取10个 5.排序 select * from tb1 order by id desc; #从大到小 select * from tb1 order by id asc; #从小到大 select * from tb1 order by age desc,id desc; #先按age从大到小排,age相同时,按id从大到小排 select * from tb1 order by id desc limit 10; #倒序排+分页,取后10个数据 6.分组 分组常用的函数有:count,max,min,sum,avg select count(id),max(id),part_id from userinfo group by part_id; #按照part_id进行分组;count可表示聚合后有几人,count哪一列都行,count(1)常用;max可聚合后,取最大的数作为id号。 注:对于聚合函数结果进行二次筛选时,条件where应改为having,如下 select count(id),part_id from userinfo where id>0 group by part_id having count(id)>1; 注:进行多次筛选时,先wheregroup byhaving

    三、连表操作

    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时,隐藏此行 注:当左右连接时,假如有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)
    Processed: 0.030, SQL: 8