sql >> Databasteknik >  >> RDS >> Mysql

mysql VÄLJ det bästa av varje kategori i en enda tabell

Prova detta:

SELECT gamers.*
FROM gamers
INNER JOIN 
 (SELECT 
   max(score) as maxscore, 
   gameid from gamers
   GROUP BY gameid) AS b
ON (b.gameid = gamers.gameid AND b.maxscore=gamers.score) ;
ORDER BY score DESC, gameid;

Detta kommer att mata ut:

+---------+--------+-------+
| gamerid | gameid | score |
+---------+--------+-------+
|       4 |      1 |    90 |
|       5 |      2 |    40 |
|       8 |      3 |    30 |
+---------+--------+-------+
3 rows in set (0.00 sec)

Det andra alternativet du kan göra är att skapa en tillfällig tabell eller en vy (om du inte gillar underfrågan).

create temporary table games_score (
 SELECT max(score) as maxscore, gameid FROM gamers GROUP BY gameid
);

Sedan:

SELECT gamers.* 
FROM gamers 
INNER JOIN games_score AS b ON (b.gameid = gamers.gameid AND b.maxscore=gamers.score) 
ORDER BY score DESC, gameid;

ELLER en vy:

create or replace view games_score AS 
SELECT max(score) as maxscore, gameid FROM gamers GROUP BY gameid;

Sedan:

SELECT gamers.* 
FROM gamers 
INNER JOIN games_score AS b ON (b.gameid = gamers.gameid AND b.maxscore=gamers.score) 
ORDER BY score DESC, gameid;


  1. Hur konfigurerar jag DbContext för att fungera med Oracle ODP.Net och EF CodeFirst?

  2. Hur man låser mysql-tabeller i php

  3. Simple Encrypted Arithmetic Library (SEAL) och sigill::Ciphertext-variabeln

  4. Nifi PutSQL Tidstämpel/Datetime-fel kan inte konverteras fel