看了mysql 查询实战2-题目-CSDN博客的题目,继续进行解答。
6、查询⽹站访问⾼峰期
目标: 查询网站访问高峰时期,高峰时期定义:至少连续三天访问量>=1000
1,关联查询
要连续三天,至少要声明“自身”三个去判断
select distinct a.* from visit_summary as a,visit_summary as b,visit_summary as c
where a.visit_sum>=1000 and b.visit_sum>=1000 and c.visit_sum>=1000
and
(
a.id=b.id-1 and b.id=c.id-1
or
b.id=a.id-1 and a.id=c.id-1
or
b.id=c.id-1 and c.id=a.id-1
) order by id ;
2,用变量的方式处理
select * from(
select *,@flag:=if((count>=3 or @flag=1) and count>0,1,0) as flag
from(
select *,@count:=if(visit_sum>=1000,@count+1,0) as count
from visit_summary
) as tmp order by id desc
) as tmp where tmp.flag=1 order by tmp.id;
如果是连续4天,5天,6天呢?这情况,用变量就很有优势了。用sql写,不断关联自身n次的话,sql就很繁杂了。
7、查询表中⾄少连续三次的数字
1,关联查询:
要连续三次,还是要声明“自身”三个去判断
select distinct a.number
from numbers as a, numbers as b,numbers as c
where a.id=b.id-1 and b.id=c.id-1 and a.number=b.number
and b.number=c.number;
2,用变量的方式
select distinct number from(
select *,@count:=if(@pre=number,@count+1,1) as count,@pre:=number as pre from
numbers, (select @count:=0,@pre:=null) v
) as tmp where tmp.count >= 3;
8、交换座位
目标:实现座位的交换,如果总数是奇数,那最后⼀⾏就不要交换了
1,异或判断
异或(XOR)操作通常用于二进制数据,可以通过使用^操作符来实现。异或运算符常用于比较不同位,即只有一位不同的值,返回1,否则返回0
select 0^1, 1^1, 2^1, 3^1, 4^1, 5^1;
2,关联查询
select a.seat_id, coalesce(b.name,a.name) as name
from seat_plan a left join seat_plan b
on b.seat_id=(a.seat_id-1)^1+1
order by a.seat_id;
3,用取余的方式去处理
select (
case when mod(seat_id,2)!=0 and seat_id!=total then seat_id+1
when mod(seat_id,2)!=0 and seat_id=total then seat_id
else seat_id-1
end
) as id, name
from seat_plan,(select count(1) as total from seat_plan) as tmp
order by id;
这个比较难想到,写起来也麻烦。
9、查询销售额较昨⽇上升的记录
1,关联自身进行比较
select b.* from sale as a,sale as b
where datediff(b.record_date, a.record_date)=1 and
b.ammount > a.ammount;
2,用变量方式
select id,record_date,ammount from
(
select *,@flag:=if(ammount>@pre,1,0) as flag,@pre:=ammount as pre from (select
@flag:=0,@pre:=null) as v, sale order by record_date
) as tmp where flag=1;
10、查询投票结果的排名情况
即第一名、第二名是谁,或者理解为,按倒序排好后,加个序号(区别就是同值的,排名是一样的)。
1,关联比较
要加一列,统计投票数大于当前行的
select *,(select count(b.votes) from vote as b where b.votes>=a.votes) as
ranking from vote as a order by votes desc;
2,用变量等方式
SELECT id, NAME, votes, ranking FROM (
SELECT *, @same:=IF(votes=@pre, @same+1,0) AS same,
@ranking:=IF(votes=@pre, @ranking, @ranking+1+IF(@sumSame > 0, @sumSame,0)) AS ranking,
@pre:=votes AS pre, @sumSame:=@same AS sunSame
FROM (SELECT @ranking:=0,@same:=0,@pre:=NULL,@sumSame:=NULL
) AS v,vote ORDER BY votes DESC
) AS temp;
这边排名,用变量的方式就显得比较繁琐了,用sql就简单很多。
总结:
对于有比较的,除了用sql,也考虑用变量的方式,看下哪种方式会更方便?目前来看,出现多次的这种的,用变量会更简便,不用反复自身关联。
上一篇:《mysql 查询实战2-题目-CSDN博客》
下一篇:《mysql 查询实战3-题目》