0

I do have a mysql product table with the columns of id, name, description, and category_id.

This is the result when it select id, name and category_id.

+----+-------------+----------------------------+
| id | category_id | name                       |
+----+-------------+----------------------------+
|  6 |           1 | category name              |
|  7 |           2 | category name              |
|  8 |           3 | category name              |
|  9 |           2 | category name              |
| 11 |           2 | category name              |
| 15 |           3 | category name              |
| 13 |           4 | category name              |
| 14 |           1 | category name              |
| 15 |           2 | category name              |
| 16 |           2 | category name              |
| 17 |           3 | category name              |
| 18 |           4 | category name              |
| 19 |           1 | category name              |
+----+-------------+----------------------------+

My question is, Just I need to select newly added 4 products from above table. These 4 products should be 4 different categories.

This is how I tried it. But its not working for me.

SELECT p.id
         , p.category_id
         , p.name
         , p.description
FROM products p
WHERE p.category_id IN ('1', '2', '3', '4') 
ORDER BY added_date DESC
LIMIT 4 

+----+-------------+--------+-------------+
| id | category_id | name   | description |
+----+-------------+--------+-------------+
|  8 |           4 | dfadff | dfasf       |
|  7 |           4 | dffdsf | fdfdfaf     |
|  6 |           3 | fdfdsf | fdsfdsfd    |
|  5 |           2 | dffdsf | dfsfsf      |
+----+-------------+--------+-------------+
4 rows in set (0.00 sec)

Result from above query:

user3733831
  • 2,886
  • 9
  • 36
  • 68
  • possible duplicate of [Retrieving the last record in each group](http://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group) – Strawberry Aug 25 '15 at 06:30

1 Answers1

2

You have to first decide which product is the "last" for each category, that can be simple max(id) if your id is autoincrementing. Then you pick products by these ids:

select p.id, p.category_id, p.name
from products p
join (
  select max(id) id from products group by category_id
) tmp using(id);

It can be seen in action at http://sqlfiddle.com/#!9/c86fa/2

If you need to check the WHERE p.category_id IN ('1', '2', '3', '4') part, it is enough to put it inside the subquery.

jkavalik
  • 1,296
  • 11
  • 21