This is the sequence of my MySql Query executions:
Query 1 : SET @channel_rank = 0;
Query 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;
Sample 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
Over here I have to execute SET @channel_rank = 0;
first in order to assign the variable (@channel_rank
) to 0. My question is HOW, inside the query 2
can I assign the the variable (@channel_rank
) to 0 initially making the second query
independent of the first
one.
The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.
We can set some value to the variable with the help of SET command. SET @yourVariableName=value; Note − In the SELECT statement, the “yourVariableName” contains the NULL value and after using the SET command it contains the value which we have given.
MySQL variable assignment There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.
You don't have to initialize the variable in the subquery. You can instead initialize the variable using 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With