在mysql中创建一个每组行数为N的视图

时间:2014-05-14 12:48:15

标签: mysql

我需要创建一个视图,该视图存储来自另一个userId作为其列之一的每个userId的前200行。 找到了一种在SELECT中使用用户定义变量来实现此目的的方法,但是MySQL不允许在SELECT中使用变量的视图。

这是视图中使用的SELECT语句的一部分:

select *,@num:= if(@userId = userId, @num + 1, 1) as row_number,
@userId := userId as dummy from (SELECT @userId:=0, @num:=0) as init

是否可以用功能替换@userId@num?类似的例子会有很大的帮助!!

1 个答案:

答案 0 :(得分:0)

考虑以下内容......

SELECT * FROM results;
+----+------------+--------+-------+-------+
| id | discipline | member | event | value |
+----+------------+--------+-------+-------+
|  1 |          1 |      2 |     4 |    10 |
|  2 |          1 |      1 |     4 |     8 |
|  3 |          1 |      2 |     5 |     9 |
|  4 |          2 |      3 |     5 |     9 |
|  5 |          1 |      2 |     6 |    11 |
|  6 |          1 |      2 |     7 |    11 |
|  7 |          1 |      2 |     1 |    11 |
|  8 |          1 |      2 |     3 |     7 |
|  9 |          1 |      1 |     8 |     8 |
+----+------------+--------+-------+-------+

说我想获得前三名'价值'每个成员的结果。如果出现平局,我会采取较低的“事件”。第一...

SELECT x.*
     , COUNT(*) rank
  FROM results x 
  JOIN results y 
    ON y.member = x.member 
   AND (y.value > x.value OR (y.value = x.value AND y.event <= x.event)) 
 GROUP 
    BY x.member
     , x.value
     , x.event 
HAVING COUNT(*) <=3;
+----+------------+--------+-------+-------+---------+
| id | discipline | member | event | value | rank    |
+----+------------+--------+-------+-------+---------+
|  2 |          1 |      1 |     4 |     8 |       1 |
|  9 |          1 |      1 |     8 |     8 |       2 |
|  7 |          1 |      2 |     1 |    11 |       1 |
|  5 |          1 |      2 |     6 |    11 |       2 |
|  6 |          1 |      2 |     7 |    11 |       3 |
|  4 |          2 |      3 |     5 |     9 |       1 |
+----+------------+--------+-------+-------+---------+
相关问题