使用选择查询增加变量值

时间:2018-06-18 09:40:51

标签: mysql

我当前的查询:

select IFNULL(max(rank),0) from (SELECT  date,if(field1 != '1',@rownum := ifnull(@rownum,0)+ 1,@rownum := ifnull(@rank,0))AS rank FROM callinfo as t where t.date > CONVERT_TZ(NOW(), @@session.time_zone, '+0:00') + INTERVAL -600 SECOND  AND t.date <= CONVERT_TZ(NOW(), @@session.time_zone, '+0:00') AND user_id = 16 order by date) as x;

以上查询有子查询:

SELECT  date,if(field1 != '1',@rownum := ifnull(@rownum,0)+ 1,@rownum := ifnull(@rank,0))AS rank FROM callinfo as t where t.date > CONVERT_TZ(NOW(), @@session.time_zone, '+0:00') + INTERVAL -600 SECOND  AND t.date <= CONVERT_TZ(NOW(), @@session.time_zone, '+0:00') AND user_id = 16 order by date

在第一次运行中给出输出:

+-----------------------------+------+
| date                        | rank |
+-----------------------------+------+
| 2018-06-18 09:21:34.1529314 | 1    |
| 2018-06-18 09:21:34.1529314 | 2    |
| 2018-06-18 09:21:54.1529314 | 0    |
| 2018-06-18 09:22:27.1529314 | 0    |
| 2018-06-18 09:04:21.1529313 | 1    |
| 2018-06-18 09:04:21.1529313 | 2    |
| 2018-06-18 09:23:29.1529314 | 0    |
| 2018-06-18 09:21:37.1529314 | 1    |
| 2018-06-18 09:21:37.1529314 | 2    |
+-----------------------------+------+
9 rows in set (0.00 sec)

第二轮:

+-----------------------------+------+
| date                        | rank |
+-----------------------------+------+
| 2018-06-18 09:21:34.1529314 | 3    |
| 2018-06-18 09:21:34.1529314 | 4    |
| 2018-06-18 09:21:54.1529314 | 0    |
| 2018-06-18 09:22:27.1529314 | 0    |
| 2018-06-18 09:04:21.1529313 | 1    |
| 2018-06-18 09:04:21.1529313 | 2    |
| 2018-06-18 09:23:29.1529314 | 0    |
| 2018-06-18 09:21:37.1529314 | 1    |
| 2018-06-18 09:21:37.1529314 | 2    |
+-----------------------------+------+
9 rows in set (0.00 sec)

问题:

  1. 在这里我们可以看到第一次运行的子查询提供了1,2结果,而在第二次运行中,它给前两行提供了3,4。所以两种情况都应该相同。

  2. 这里我试图从查询中获得最大排名,因此输出应该是排名列中的最大值。

  3. 但在这两种情况下,它都没有按预期工作。 有人喜欢帮忙吗?

0 个答案:

没有答案