PHP PDO - Using MySQL Variables

前端 未结 1 1622
-上瘾入骨i
-上瘾入骨i 2020-12-11 04:48

I\'m trying to run a query in PHP using PDO. The query has some variables at the top to determine a rank, except the when using the SET @var in the $sql, it returns an empty

相关标签:
1条回答
  • 2020-12-11 04:54

    Found the solution here: https://stackoverflow.com/a/4685040/1266457

    Thank you :)

    To fix:

    // Prepare and execute the variables first
    $sql = "
    SET @prev_value = NULL;
    SET @rank_count = 0;
    SET @rank_increasing = 0;
    ";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    
    // Run the main query
    $sql = "
    SELECT a.*
         , @rank_increasing := @rank_increasing + 1 AS row_num
         , CASE
           WHEN @prev_value = score 
              THEN @rank_count
           WHEN @prev_value := score 
              THEN @rank_count := @rank_increasing
           END AS rank
      FROM ( 
           -- INLINE VIEW --
           ) a
    "; ...
    
    0 讨论(0)
提交回复
热议问题