我有以下表格:
Table "Questoes";
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| id_quest | int(11) | NO | | NULL | |
| questao | varchar(255) | NO | | NULL | |
| nivel | int(11) | NO | | NULL | |
| tipo | varchar(255) | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
Table "Resultados";
+-----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| id_user | int(11) | NO | MUL | NULL | |
| nivel | int(11) | NO | | NULL | |
| pontuacao | int(24) | NO | | NULL | |
| data | date | NO | | NULL | |
+-----------+---------+------+-----+---------+----------------+
And table "utilizador";
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id_user | int(11) | NO | PRI | NULL | auto_increment |
| id_tipo | int(11) | NO | | 1 | |
| username | varchar(50) | NO | UNI | NULL | |
| password | varchar(20) | NO | | NULL | |
| nome | varchar(50) | NO | | NULL | |
| email | varchar(100) | NO | | NULL | |
| data_nasc | text | NO | | NULL | |
| e_valido | smallint(6) | NO | | 0 | |
+-----------+--------------+------+-----+---------+----------------+
我需要的是对于最佳玩家,“resultados”表中每个级别(字段“nivel”)的得分(字段“pontuacao”)的最大值。 要获得玩家名称,将通过“resultados”表中的“id_user”字段。
我有这个,但没有工作:
SELECT u.id_user, MAX(u.pontuacao), u.nivel, u.data, l.nivel, r.id_user, r.username
FROM questoes l, resultados u, utilizador r
WHERE u.nivel = l.nivel AND r.id_tipo=1 AND u.id_user=r.id_user
GROUP BY u.nivel
答案 0 :(得分:1)
SELECT a.id_user, r.username, b.pontuacao, b.nivel
FROM resultados a
INNER JOIN utilizador r on a.id_user=r.id_user
INNER JOIN (SELECT u.nivel, MAX(u.pontuacao) pontuacao
FROM resultados u
GROUP BY u.nivel) b ON a.nivel = b.nivel AND a.pontuacao = b.pontuacao
答案 1 :(得分:1)
它不起作用,因为你依赖于MySQL的扩展,它没有达到预期的效果。使用group by
时,只需确保汇总select
或group by
中的所有列。
你想要的更像是:
SELECT u.id_user, r2.pontuacao, u.nivel, u.data, l.nivel, r.id_user, r.username
FROM questoes l join
resultados u
u.nivel = l.nivel join
utilizador r
on u.id_user = r.id_user join
(select r2.nivel, max(r2.pontuacao) as maxp
from resultados r2
group by r2.nivel
) r2
on u.nivel = r2.nivel and u.pontuacao = r2.maxp
WHER r.id_tipo = 1
GROUP BY u.nivel;
这会将最大值计算为子查询,然后将其重新加入。在此之后您可能不需要group by
。另外,我修复了连接,因此它们使用了正确的ANSI语法。