0

please help as this is turning into a week of almost no sleep already..

I have a table called Products, with these columns: id | productName | category | subcategory | date_added | price .

how can I get the ID and category from the LAST PRODUCT ADDED IN EACH SUBCATEGORY in this table?

so far this kinda works but it only returns the subcategory, and I also need the category and ID

$sql = mysql_query("SELECT DISTINCT subcategory FROM products ORDER BY id DESC LIMIT 12");

If i try something like

$sql = mysql_query("SELECT DISTINCT id, category, subcategory FROM products ORDER BY id DESC LIMIT 12");

it just returns everything..

Thank you all

4
  • Have a sub-query that returns last product for each sub-category. Join with that result. Commented Dec 5, 2016 at 8:27
  • provide your table structure with sample data's Commented Dec 5, 2016 at 8:29
  • 1
    don't use mysql_-functions, they are outdated, deprecated, and in PHP7 removed. use mysqli_ or PDO instead. Commented Dec 5, 2016 at 8:29
  • @NewbeeDev the first line of his post haha, he needs some sleep! Commented Dec 5, 2016 at 8:33

4 Answers 4

1

First: group them by subcategory

GROUP  BY subcategory

then set your condition to id = (select your id of latest product according to its subcategory)

id = (SELECT id 
         FROM   products 
         WHERE  products.subcategory = Product.subcategory 
         ORDER  BY created DESC 
         LIMIT  1) 

So your query would be like this

SELECT * 
    FROM   products Product 
    WHERE  id = (SELECT id 
                 FROM   products 
                 WHERE  products.subcategory = Product.subcategory 
                 ORDER  BY created DESC 
                 LIMIT  1) 
GROUP  BY subcategory

enter image description here enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Mate, what you have done here was way beyond my expectations :))) Thank you, you have saved me! you understood the entire problem better than anyone that I've asked before .. and the tables and everything.. pfff.. THANK YOU!!
0

try this

SELECT * FROM `products` GROUP BY subcategory ORDER By id DESC

MySQL extension is deprecated and removed from php7 so use mysqli or PDO

Comments

0

Change your query to

SELECT id, category, subcategory FROM products GROUP BY (subcategory) ORDER BY id DESC LIMIT 12

Comments

0

if id is AUTO_INCREMENT, you can do this:

SELECT * FROM `products` WHERE id IN ( SELECT MAX(id) FROM `products` GROUP BY subcategory)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.