mysql总结

一道面试题:
有如下表和数组,把num值处于[20-29]之间改为20,num值处于[30-39]之间的改为30
num数有:3,12,15,25,23,27,37,35,32,47,58
mysql语句:
create table mian (
num int
);
insert into mian values (3),(12),(15),(25),(23),(27),(37),(35),(32),(47),(58);

updata mian set floor(num/10)*10 where num>=20 and num <=39;

练习题:
把good表中商品名‘诺基亚xxxx’的商品改为‘HTCxxxx’,
提示:大胆的把列看成变量,参与运算,甚至调用函数来处理
substring();concat;

练习题;
+--------+---------+-------+
| name   | subject | score |
+--------+---------+-------+
| 张三   | 数学    |    90 |
| 张三   | 语文    |    50 |
| 张三   | 地理    |    40 |
| 李四   | 语文    |    55 |
| 李四   | 政治    |    45 |
| 王五   | 政治    |    30 |
+--------+---------+-------+
求挂科大于等于2以上的平均分?

create table result(
name varchar(20) not null default '',
subject varchar(20) not null default '',
score varchar(20) not null default ''
);
 insert into result values('张三','数学',90),('张三','数学',90),('张三','语文',50),
('张三','地理',40),('李四','语文',55),('李四','政治',45),('王五','政治',30);
 
正解:第一步:查询所有平均分
select name,avg(score) from result grounp by name;
第二步:计算出每个人挂科情况
select name,subject,score,score<60 as gks from result;
如上:挂科数目结果:
select name,subject,score,score<60 as gks from result group by name;
每个人的平均分及挂科数在晒选一下:
select name,avg(score),sum(score<60 )as gks from result group by name
 having gks>=2;


第二种解法:
select name,count(1) from result where score<60;

select name,count(1) as gks from result
where score<60
group by name
having gks>=2;
把上面的结果集当成一张表
select name from(select name,count(1) as gks from result
where score<60
group by name
having gks>=2)
as tmp;

select name,avg(score) from result
where name in ('张三','李四')
group by name;

最终代码 这个列子用到了子查询,并且嵌套,麻烦
如果group,having用到熟悉,一条sql语句就能完成:
select name,avg(score) from result
where name in (select name from(select name,count(1) as gks from result
where score<60
group by name
having gks>=2)
as tmp)
group by name;

为什么建表时,加not null default '',default 0?
答:不想让表中出现null值
为什么不想要null值?
答:不好比较;

posted @ 2018-11-12 18:13  枫叶码甲  阅读(164)  评论(0编辑  收藏  举报