Search code examples
mysqlgroup-bysql-order-bylimit

MySQL - GROUP results BY a single column alongside ORDER BY and LIMIT


I want to select a list of tasks from my database. The tasks have a category_id. I want to get a singlur task per category_id. So if I, for example, had 10 tasks that are linked to like 6 categories that would result in 6 results. The 6 results I want are determined by their id, the lowest id among the GROUP BY is the correct record for that GROUP. Also the maximum result set can be no larger than 20 ('LIMIT').

SELECT * FROM `task` WHERE `datetime`<NOW()  `task_status_id`=1 GROUP BY `category_id` ORDER BY `id` ASC LIMIT 20

What is wrong with the above query, I got no clue, I'm also at a loss getting any google results for this.

ADDED LATER

http://sqlfiddle.com/#!9/fa39cf

CREATE TABLE `category` (
  `id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `category` (`id`) VALUES
(1),
(2),
(3);


CREATE TABLE `task` (
  `id` int(10) UNSIGNED NOT NULL,
  `category_id` int(10) UNSIGNED NOT NULL,
  `task_status_id` int(10) UNSIGNED DEFAULT '1',
  `datetime` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `task` (`id`, `category_id`, `task_status_id`, `datetime`) VALUES
(3, 2, 1, '2018-07-24 11:20:26'),
(4, 2, 1, '2018-07-24 11:20:26'),
(5, 3, 1, '2018-07-24 11:21:35'),
(6, 3, 1, '2018-07-24 11:21:35');

Solution

  • You can try first finding the smallest id for each category and then joining it with the task table to get the remaining details.

    SELECT t.* FROM task t 
    JOIN (SELECT category_id, min(id) id from task group by category_id) tc 
        ON (t.id = tc.id)
    LIMIT 20