使用hasAndBelongsToMany表关系时,如何按用户流行度排序?即:
我有一个名为playgroups,players和playgroup_players的表。
如何根据游戏组中的玩家数量对游戏小组进行排序?
游戏小组:
CREATE TABLE `playgroups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`tag` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`avatar_url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`city` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`state` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
玩家:
CREATE TABLE `players` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(30) DEFAULT NULL,
`last_name` varchar(30) DEFAULT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`public_email` tinyint(1) NOT NULL DEFAULT '0',
`facebook_id` varchar(250) DEFAULT NULL,
`card_tooltip` tinyint(1) NOT NULL DEFAULT '1',
`profile_pic_url` varchar(255) NOT NULL,
`public_name` tinyint(1) NOT NULL DEFAULT '0',
`city` varchar(40) NOT NULL,
`state` varchar(2) NOT NULL,
`date_joined` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=107 DEFAULT CHARSET=latin1;
和PlaygroupPlayers:
CREATE TABLE `playgroup_players` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`player_id` int(11) NOT NULL,
`playgroup_id` int(11) NOT NULL,
`admin` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
答案 0 :(得分:2)
SELECT PP.playgroup_id, COUNT(*) cnt
FROM playgroup_players PP
GROUP BY PP.playgroup_id
ORDER BY COUNT(*) DESC
这将为您提供一个游戏组列表,其中至少有一个玩家按玩家数量排序。当然,字段名称组成:)
SELECT G.playgroup_id, COUNT(PP.playgroup_id) cnt
FROM playgroup G
LEFT OUTER JOIN playgroup_players PP ON (PP.playgroup_id=G.playgroup_id)
GROUP BY G.playgroup_id
ORDER BY COUNT(*) DESC
这应该会为您提供所有游戏组的列表(即使是没有玩家的游戏组)。我已经在Oracle和我自己的一些数据上进行了测试,并且可以正常运行
答案 1 :(得分:1)
SELECT playgroups.*, d1.num_players
FROM playgroups
LEFT OUTER JOIN (
SELECT playgroup_id, count(*) as num_players
FROM playgroup_players
GROUP BY playgroup_id
) d1
ON playgroups.id = d1.playgroup_id
ORDER BY d1.num_players DESC
内部查询(a.k.a派生表)为您提供每个游戏组的计数。外部查询将其连接回playgroups
中的主记录。如果您需要访问playgroups
中的非汇总列,则需要此表单。
答案 2 :(得分:0)
我认为这个查询应该有用。
SELECT pgp.playgroup_id, COUNT(pgp.id)
FROM playgroups_players pgp
GROUP BY pgp.playgroup_id
ORDER BY count(pgp.id)