我试图通过聚合函数获取排名值 - 我想看看它是否可以在MySQL查询中完成(而不是ORM调用查询)。
我拥有的表和数据类似于:
/bin/ls
到目前为止,我有:
CREATE TABLE `interactions` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`account` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
INSERT INTO `interactions` VALUES
(1, "xyz", "2017-01-01 00:05:01"),
(2, "xyz", "2017-01-01 00:05:10"),
(3, "abc", "2017-01-01 00:05:21"),
(4, "xyz", "2017-01-01 00:05:43"),
(5, "def", "2017-01-01 00:05:47"),
(6, "xyz", "2017-01-01 00:05:49"),
(7, "abc", "2017-01-01 00:05:50"),
(8, "abc", "2017-01-01 00:05:59");
但是这会输出每个帐户(具有正确的set @curRank := 0;
select
@curRank := @curRank + 1 AS rank,
der.account,
der.searches
from
interactions
right join
(select account, count(id) AS searches from interactions group by account order by searches) AS der
on
der.account = interactions.account;
值 - 但排名不止一次):
searches
我正在寻找:
1 abc 3
2 abc 3
3 abc 3
4 def 1
5 xyz 4
6 xyz 4
7 xyz 4
8 xyz 4
我应该提一下,我不关心联合排名 - 如果两个账户在表格中以相同的数量结束,那么如果他们一个接一个地排名(或者什么是什么)并不重要顺序)。
答案 0 :(得分:0)
向SELECT添加DISTINCT会修复查询:
set @curRank := 0;
select distinct
der.account,
der.searches,
@curRank := @curRank + 1 AS rank
from
interactions
right join
(select account, count(id) AS searches from interactions group by account order by searches) AS der
on
der.account = interactions.account;