mysql一个查询来显示视图中的趋势

时间:2010-07-08 20:34:28

标签: sql mysql

我有一个每小时运行的cron作业。

cron作业为表'update'添加记录

table - 'update'
update_id (primary)
timestamp

将我网站的每个页面的记录添加到表格视图中

table - 'views'
page_id
update_id
view_count

我希望实现的是一个查询,它可以将每个page_id的最新更新(最高update_id)与之前的更新进行比较,并返回视图的百分比增加。不能为我的生活让我头晕目眩。

以下是一些示例数据。

page_id = 1
update_id = 10
view_count = 1251

page_id = 1
update_id = 11
view_count = 1349

2 个答案:

答案 0 :(得分:1)

您可能想尝试加入views上的update_id - 1表,如以下查询中所示:

SELECT    v1.page_id,
          v1.view_count latest_count,
          v2.view_count previous_count,
          (1 - v2.view_count / v1.view_count) * 100 trend_perc
FROM      views v1
JOIN      views v2 ON (v2.update_id = v1.update_id - 1 AND 
                       v2.page_id = v1.page_id)
WHERE     v1.update_id = (SELECT MAX(update_id) FROM `views`)
GROUP BY  v1.page_id
ORDER BY  page_id;

测试用例:

CREATE TABLE `updates` (update_id int, timestamp datetime);
CREATE TABLE `views` (page_id int, update_id int, view_count int);

INSERT INTO `updates` VALUES (1, '2010-07-08 12:00:00');
INSERT INTO `updates` VALUES (2, '2010-07-08 13:00:00');
INSERT INTO `updates` VALUES (3, '2010-07-08 14:00:00');

INSERT INTO `views` VALUES (1, 1, 100);
INSERT INTO `views` VALUES (2, 1, 50);
INSERT INTO `views` VALUES (3, 1, 75);
INSERT INTO `views` VALUES (1, 2, 150);
INSERT INTO `views` VALUES (2, 2, 90);
INSERT INTO `views` VALUES (3, 2, 80);
INSERT INTO `views` VALUES (1, 3, 175);
INSERT INTO `views` VALUES (2, 3, 115);
INSERT INTO `views` VALUES (3, 3, 120);

结果:

+---------+--------------+----------------+------------+
| page_id | latest_count | previous_count | trend_perc |
+---------+--------------+----------------+------------+
|       1 |          175 |            150 |    14.2857 |
|       2 |          115 |             90 |    21.7391 |
|       3 |          120 |             80 |    33.3333 |
+---------+--------------+----------------+------------+
3 rows in set (0.00 sec)

请注意,如果trend_perc恰好是NULL,则previous_count将为0

答案 1 :(得分:0)

我想你需要首先聚合update表,所以,

SELECT COUNT(*) AS cnt FROM `update` WHERE update_id = (SELECT MAX(update_id) FROM `update`) GROUP BY page_id;

然后你想要一个带视图的连接

SELECT * FROM views AS v1 ...

......呃,等等。我想你在update表中缺少一栏,不是吗? page_id。

CREATE TEMPORARY TABLE vTemp 
SELECT page_id, COUNT(*) AS cnt FROM `update` WHERE update_id = (SELECT MAX(update_id) FROM `update`) GROUP BY page_id;

然后你想要一个有视图的连接:

SELECT 1 - (v1.view_count / vTemp.cnt) AS difference FROM views AS v1 
  LEFT OUTER JOIN vTemp AS v2 USING(page_id)
WHERE v1.update_id = (SELECT MAX(update_id)-1 FROM `update`) GROUP BY page_id

或者......