辛星解读一次在mysql中获取排名的实例

     这里并没有考虑到绑定,因此我们还是使用拼凑sql语句的形式,而且并不是在mysql命令行中书写的,很多条件我们都直接用具体的数据来代替。

     首先交代一下需求:

     (1)作业保存在t_score表中,练习保存在t_exercise表中。

     (2)我们需要从练习表和作业表中取出对应的学生成绩,而学生信息保存在t_user表中。

     (3)需要知道某个学生根据某道题的正答率和时间来获取对应的排名。

   

     然后交代一下基本知识:

     (1)对于排名,这里没有记录到表中,我们使用的是@x的变量的形式,需要注意的是@x变量这种是对connection有效的,也就是它是对不同的连接有不同的值的。

      (2)对于子查询的时候必须给被导出的表指定别名,否则会报错。

 

     然后我们可以分三级来做这件事:

     (1)首先把练习表和作业表的内容统一取出,得到一个新表的统一结构,代码如下:

    

 $sqlt = "(select ubint64_student_no,char64_integral,
          	char64_testbank_num,char64_activities_time from t_score
          	where char64_activities_no = '$gid' 
          	and char64_testbank_no = '$tbno') 
			union (select ubint64_student_no,char64_integral,
			char64_testbank_num,char64_activities_time from t_exercise
			where char64_activities_no = '$gid' 
          	and char64_testbank_no = '$tbno')  ";

   

    (2)然后取得所有的排名信息,代码如下:


 $sqlz = " ( SELECT @rank := @rank + 1 as rank, 
          	t_user.ubint64_no,char64_user_name, 
          	max(char64_integral/char64_testbank_num) as right_rate,
          	min(char64_activities_time) as right_time 
          	from ( $sqlt ) as t ,t_user ,(select @rank := 0) b
          	where t.ubint64_student_no = t_user.ubint64_no 
          	group by t_user.ubint64_no ) ";


    (3)最后获取某个学生的成绩,代码如下:


$sqly = "select * from ($sqlz) as xin where ubint64_no = 272";


  (4)最后我们来看一下生成的代码吧:

select * from ( ( SELECT @rank := @rank + 1 as rank, t_user.ubint64_no,char64_user_name, max(char64_integral/char64_testbank_num) as right_rate, min(char64_activities_time) as right_time from ( (select ubint64_student_no,char64_integral, char64_testbank_num,char64_activities_time from t_score where char64_activities_no = '4' and char64_testbank_no = '1') union (select ubint64_student_no,char64_integral, char64_testbank_num,char64_activities_time from t_exercise where char64_activities_no = '4' and char64_testbank_no = '1') ) as t ,t_user ,(select @rank := 0) b where t.ubint64_student_no = t_user.ubint64_no group by t_user.ubint64_no ) ) as xin where ubint64_no = 272

    当然啦,这里只是一个demo,只是为了完成需求而写的一个示范代码,不建议直接拿到代码中直接使用,而且在使用它之前应该进行严格的参数过滤,而且还要使用绑定机制。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值