MySql: initialize the mySql variable inside the query

This is the sequence of my MySql execution requests:

Request 1 :SET @channel_rank = 0;

Request 2:

  SELECT time_of_day, @channel_rank := IF(
        @current_channel = channel,
        1,
        @channel_rank + 1
      ) AS channel_rank , 
      @current_channel := channel AS channel,Views
    FROM
    (
    SELECT @channel_rank = 0,time_of_day,channel, SUM(Views) AS 'Views'
      FROM access_logs_meaningful_optimized
      WHERE `time_of_day` = 0
      AND playing_date = '2016-10-26' GROUP BY channel
      ORDER BY SUM(views) DESC
      LIMIT 5
     ) xx; 

Example result:

time_of_day  channel_rank  channel                Views   
-----------  ------------  ---------------------  --------
          0             1  Tolo                   1291    
          0             2  Tolo News              855     
          0             3  Samaa News             805     
          0             4  Ary Digital            695     
          0             5  Dunya News             653     

Here I must first execute SET @channel_rank = 0;to assign the variable ( @channel_rank) to 0. My question is HOW , inside Can I assign the variable ( ) to 0, initially making it independent of . query 2@channel_rank second query first

+4
source share
1 answer

You do not need to initialize the variable in the subquery. Instead, you can initialize the variable with CROSS JOIN:

SELECT time_of_day, 
       @channel_rank := IF(@current_channel = channel, 1, 
                             @channel_rank + 1) AS channel_rank, 
       @current_channel := channel AS channel,Views
FROM
(
   SELECT time_of_day,channel, SUM(Views) AS 'Views'
   FROM access_logs_meaningful_optimized
   WHERE `time_of_day` = 0
   AND playing_date = '2016-10-26' 
   GROUP BY channel
   ORDER BY SUM(views) DESC
   LIMIT 5
) AS xx
CROSS JOIN (SELECT @channel_rank := 0) var
+3
source

Source: https://habr.com/ru/post/1659033/


All Articles