mysql – group by вместе с order by

Question:

Multilanguage of the site is made by displaying more popular values ​​from the mysql database that have collected a larger number of votes.

The table consists of:

|id|text_id|module|lang| text |voices|uid|
------------------------------------------
|1 |   1   |anketa| ru |Ашибка|   1  | 1 |
------------------------------------------
|2 |   1   |anketa| ru |Ошибка|   2  | 2 |

I got a request:

SELECT *
FROM `langs` 
WHERE `module`='anketa' 
  AND `lang`='ru' 
GROUP BY `text_id` 
ORDER BY `voices` DESC

But it outputs the first value, which is the first in the list with the minimum number of voices , but should only display the value with the largest number of voices.

Help me write the correct request.

Answer:

Solution of the problem:

SELECT
    `l`.`text_id`, `l`.`text`, `l`.`voices`
FROM `langs` `l`
INNER JOIN (
    SELECT
        `text_id`, MAX(`voices`) AS `MaxVoice`
    FROM `langs`
    WHERE `module`='anketa' AND
    `lang`='ru'
    GROUP BY `text_id`
) `lm`
ON `l`.`text_id` = `lm`.`text_id` AND
   `l`.`voices` = `lm`.`MaxVoice` AND
   `l`.`module` = 'anketa' AND
   `l`.`lang` = 'ru'
GROUP BY `l`.`text_id`
ORDER BY `l`.`text_id` ASC
Scroll to Top