I have a database with an Items
table that looks something like this:
id
name
category (int)
There are several hundred thousand records. Each item
can be in one of 7 different categories
, which correspond to a categories
table:
id
category
I want a query that chooses 1 random item, from each category. Whats the best way of approaching that? I know to use Order By rand()
and LIMIT 1
for similar random queries, but I've never done something like this.
Please note: in the following example I am assuming your table is named "items" not "Items" because you also said the other table was named "categories" (second table name not capitalized).
The SQL for what you want to do would roughly be:
Try this
REF: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
This query returns all items joined to categories in random order:
To restrict each category to one, wrap the query in a partial
GROUP BY
:Note that when a query has both
GROUP BY
andORDER BY
clause, the grouping is performed before sorting. This is why I have used two queries: the first one sorts the results, the second one groups the results.I understand that this query isn't going to win any race. I am open to suggestions.
Here is a simple solution. Let suppose you have this table.
Use this query