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 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误