Tuesday, 2 June 2015

Mysql: Select latest one from each category (group-wise max in a group query)

Suppose we have this 'catalogs' table 
CREATE TABLE catalogs(
  id INT(11) NOT NULL,
  cat_id INT(11) DEFAULT NULL,
  name VARCHAR(50) DEFAULT NULL,
  `date` DATE DEFAULT NULL,
  PRIMARY KEY (id)
);
INSERT INTO catalogs VALUES 
  (1, 1, 'suzy', '2011-09-15'),
  (2, 2, 'andy', '2011-10-01'),
  (3, 1, 'dony', '2010-12-25'),
  (4, 3, 'harry', '2010-01-05'),
  (5, 2, 'matty', '2011-06-01'),
  (6, 3, 'samy', '2010-11-02'),
  (7, 1, 'honey', '2011-10-03');

This query will select the latest one from each category -

SELECT t1.cat_id, t1.id FROM catalogs t1
  JOIN (
        SELECT cat_id, MAX(date) last_date FROM catalogs
          GROUP BY cat_id
        ) t2
    ON t1.cat_id = t2.cat_id AND t1.date = t2.last_date
ORDER BY t1.cat_id;
+--------+----+
| cat_id | id |
+--------+----+
|      1 |  7 |
|      2 |  2 |
|      3 |  6 |
+--------+----+

Other way with single query
SELECT 
cat_id
,SUBSTRING_INDEX(GROUP_COCNAT(id ORDER BY date DESC),',',1) AS max_date_id
FROM 
catalogs
GROUP BY
cat_id;

0 comments:

Post a Comment