I have these 2 tables
categories with fields “id, category, total”
users with fields “id, category_id, title”
Category is a list of categories that a user can select.
Every time a user pick a certain category, we increment the total counter. (i.e popularity)
How can I grab a unique user data per category based ordered by categories.total and also the user.id needs to be the latest?
This is what I have. Almost there except this grabs the first user id.
select users.id from users left join categories on users.category_id = categories.id group by users.category_id order by categories.total desc
To illustrate, here is an example:
categories table has the following values
id = 1, category = free, total = 3
id = 2, category = expensive, total = 1
id = 3, category = cute, total = 2
users table has the following values
id = 1, category_id = 1, title = aello
id = 2, category_id = 2, title = bello
id = 3, category_id = 3, title = zello
id = 4, category_id = 1, title = gello
id = 5, category_id = 3, title = cello
id = 6, category_id = 1, title = fello
The sql query that I have returns the following users: 1, 3, 2 (the first user to be associated with the category that has the most total)
However, what I want the result to be is: 6, 5, 2 (the LAST user to be associated with the category that has the most total)
Thanks,
Tee
Your requirements confuse me… so I’m not sure if this will really accomplish what you want… but it should return (6,5,2) (in no particular order). Add “ORDER BY category_id” or something, if ordering is important.
To address your comment, try this (untested, as I don’t have MySQL installed anywhere):