A
A
Alex Wells2017-08-11 15:46:28
MySQL
Alex Wells, 2017-08-11 15:46:28

Count group by order by 0?

Hello. There is a request:

SELECT `bot_id`, COUNT(*) AS `total`
FROM `items` 
GROUP BY `bot_id`
ORDER BY `total` ASC

Pulls the bot_id that has the smallest number of items.bot_id = bot_id.
The query itself sorts fine if bot_id has more than 0 items. It is necessary that 0 is also displayed and has priority. How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2017-08-11
@Alex_Wells

SELECT `b`.`id` AS `bot_id`, IFNULL(`c`.`count`, 0) AS `total`
  FROM (
    SELECT `bot_id`, COUNT(*) AS `count`
      FROM `items`
      GROUP BY `bot_id`
  ) AS `c`
  RIGHT JOIN `bots` AS `b` ON `b`.`id` = `c`.`bot_id`
  ORDER BY `total`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question