MySQL : Initialize mySql variable inside a query

标签 mysql sql

这是我的 MySql 查询执行顺序:

查询 1:SET @channel_rank = 0;

查询 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; 

示例结果:

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     

在这里,我必须先执行 SET @channel_rank = 0; 才能将变量 (@channel_rank) 赋值为 0。我的问题是如何,在 query 2 中,我可以将变量 (@channel_rank) 分配给 0 最初使 第二个查询 独立于第一个

最佳答案

您不必在子查询中初始化变量。您可以改为使用 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

关于MySQL : Initialize mySql variable inside a query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40279318/

相关文章:

mysql - Angular 7 : Update and Delete functions don't work

php - 如何在数据库中相应地保存 gmail 电子邮件

PHP 循环 x 次,使用 while 和 if

c# - 如何用字符串中的双撇号替换撇号?

mysql - 从插入语句返回 Query_ID

sql - 使用sql Developer从oracle读取xml标签值

mysql - 基于MySQL中的另一个表更新关系表

Mysql 表是只读的。权限、所有者已设置

php - 表 'X' 是只读的,使用 Mac,我该如何解决这个问题?

sql - 如何将xml的嵌套层次结构转换为sql表