mysql - 在有限的数据量中创建带有排名列的 View

标签 mysql

所以我有一个结构如下的 MySQL 表:

CREATE TABLE `spenttime` {
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `userid` int(11) NOT NULL,
    `serverid` int(11) NOT NULL,
    `time` int(11) NOT NULL,
    `day` int(11) NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `dbid_sid_day` (`userid`,`serverid`,`day`)
}

我存储每个注册玩家每天在游戏服务器上花费的时间。 time 是花费的时间量,以秒为单位,day 是每天的unix时间戳(一天的开始)。我想在我的数据库上创建一个 View ,该 View 将显示每个用户每周在服务器上花费的时间,但有一列显示该时间的排名,每周独立于每个服务器。例如数据(为了澄清,我将在本例中使用日期格式 Y-M-D 而不是 day 列的 unix 时间戳):

INSERT INTO `spenttime` (`userid`, `serverid`, `time`, `day`) VALUES
    (1, 1, 200, '2013-04-01'),
    (1, 1, 150, '2013-04-02'),
    (2, 1, 100, '2013-04-02'),
    (3, 1, 500, '2013-04-04'),
    (2, 2, 400, '2013-04-04'),
    (1, 1, 300, '2013-04-08'),
    (3, 1, 200, '2013-04-08');

对于 viev 中名为 spenttime_week 的数据,应该出现:

+--------+----------+--------+------------+------+
| userid | serverid |  time  |  yearweek  | rank |
+--------+----------+--------+------------+------+
|     1  |       1  |   350  | '2013-W14' |   2  |
|     2  |       1  |   100  | '2013-W14' |   3  |
|     3  |       1  |   500  | '2013-W14' |   1  |
|     2  |       2  |   400  | '2013-W14' |   1  |
|     1  |       1  |   300  | '2013-W15' |   1  |
|     3  |       1  |   200  | '2013-W15' |   2  |
+--------+----------+--------+------------+------+

我知道如何生成没有排名的 View ,我只有排名列的问题...... 我怎样才能做到这一点?

//编辑 另外,此列必须出现在 viev 中,我无法在该 View 中选择生成它,因为我将使用它的应用程序不允许...

最佳答案

首先,您需要创建第一个 VIEW,汇总每个用户在同一周所花费的时间:

CREATE VIEW total_spent_time AS
SELECT userid,
       serverid,
       sum(time) AS total_time,
       yearweek(day, 3) as week
FROM spenttime
GROUP BY userid, serverid, week;

然后您可以像这样创建 View :

CREATE VIEW spenttime_week AS
 SELECT
  s1.userid,
  s1.serverid,
  s1.total_time,
  s1.week,
  count(s2.total_time)+1 AS rank
FROM
  total_spent_time s1 LEFT JOIN total_spent_time s2
  ON s1.serverid=s2.serverid
     AND s1.userid!=s2.userid
     AND s1.week = s2.week
     AND s1.total_time<=s2.total_time
GROUP BY  
  s1.userid,
  s1.serverid,
  s1.total_time,
  s1.week
ORDER BY
  s1.week, s1.serverid, s1.userid

请看 fiddle here .

关于mysql - 在有限的数据量中创建带有排名列的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15871564/

相关文章:

Mysql drop user with grants for multiple hosts

python - Django 使用自定义 SQL 而不是模型将 JSON 对象返回到模板

php - 建立查询mysql的问题

mysql - VBScript 在同一代码中使用两个 For Next

php - 在其他代码中使用唯一值

MySql:将一列附加到另一列

php - PDO setAttribute 与 PDOException

mysql - 如何从 MySQL 返回下一个可用日期?

php excel阅读器读取数字不正确

python - 从 celery 执行插入时 mysql 命令不同步