好的,我有以下数据库:
CREATE TABLE IF NOT EXISTS `highscores` (
`lid` int(11) NOT NULL,
`username` varchar(15) NOT NULL,
`score` int(16) NOT NULL,
PRIMARY KEY (`lid`,`username`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
盖子是等级ID。
假设我在表格中有以下值:
lid, username,score
1,sam,15
1,joe,12
1,sue,6
1,josh,9
2,sam,8
2,joe,16
2,sue,4
3,sam,65
4,josh,87
4,sue,43
5,sam,12
5,sue,28
5,joe,29
and so on.
如何创建查询(或者如果需要一组查询)以获取以下内容
sam has 3 high scores
joe has 2 high scores
josh has 1 high score
提前致谢。
答案 0 :(得分:2)
我还没有测试过,但请尝试以下查询
select
concat(h.username ," has ", count(h.username)," high scores ")
from
highscores h inner join
(select lid, max(score) as maxscore
from highscores group by lid) t on h.lid = t.lid and h.score = t.maxscore
group by h.username
答案 1 :(得分:2)
根据您的描述,此查询将生成您需要的内容
SELECT username,COUNT(*) as num_highscores FROM (
SELECT lid,username
FROM highscores h1
WHERE score=(
SELECT MAX(score)
FROM highscores h2
WHERE h2.lid=h1.lid
)
) AS high_scores
GROUP BY username
ORDER BY num_highscores DESC
虽然我得到的样本数据结果不同: