dotaer1993 2016-08-10 05:13 采纳率: 100%
浏览 236
已采纳

嵌套子查询中的MySQL变量

Currently I'm working on kind of e-learning platform which contain courses and exams module. The idea is that course is followed by exam. User can solve exam few times (depending on setting in exam table). I have a module where I need to determine whether user should be redirected to exam or statistics page. If user hasn't use all his attempts he should be redirected to exam, otherwise to stats.

So here is my query (little simplified, since all conditions and joins of outer query doesn't matter here) which should determine where to go.

SELECT 
 @course_id := courses.id as id,
 IF(
      (SELECT X.attempts_count FROM
           (SELECT
           COUNT(exams_attempts.id) as attempts_count,
           @max_attempts := exams.max_attempts
           FROM exams
           LEFT JOIN exams_attempts ON exams.id = exams_attempts.quiz_id
           JOIN users ON exams_attempts.user_id = users.id
           WHERE exams_attempts.user_id = 12
           AND exams_attempts.course_id = @course_id
           HAVING attempts_count >= @max_attempts) as X
      ),
      'stats',
      'exam'
 ) as redirect 
FROM courses
WHERE courses.id = 1

For testing reasons I limited courses to a static value, but in actual usage it's big amount of courses to look up.

And finally - I discovered that this works on localhost, but not on server, despite the same MySql version. I would like to know if there is some setting that prevents my query from being executed properly. Also I would like to know what do you suggest, maybe my idea is not good and I could rebuild that query?

  • 写回答

1条回答 默认 最新

  • doutao1939 2016-08-10 05:47
    关注

    This can be made to work.

    The deal is with the following concept from the manual User-Defined Variables:

    In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second:

    SELECT @a, @a:=@a+1, ...;
    

    However, the order of evaluation for expressions involving user variables is undefined.

    And with variable cleansing. See the blog from Baron that is Obligatory Reading. Consider nested if statements and the use of least(), greatest(), and coalesce() it such efforts for safe variable handling.

    Many of these mysql-variables questions can take some time to write safely. Like an hour, or half a day. Just getting the answer right once is not equivalent to Production Ready code. I created a tag a while ago to house them as I restumble into them or write a few.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化