Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Select One Random record from each Category

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 1for similar random queries, but I've never done something like this.

like image 829
djt Avatar asked Jan 09 '13 19:01

djt


People also ask

How do I select a random row by group in SQL?

Now let's find how to do Random Sampling within Groups in SQL using RAND() function. Below SQL statement is to display rows in random order using RAND() function: Query: SELECT * FROM table_name order by RANDOM();

How do I select a random row in SQL query?

To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).


1 Answers

This query returns all items joined to categories in random order:

SELECT
c.id AS cid, c.category, i.id AS iid, i.name
FROM categories c
INNER JOIN items i ON c.id = i.category
ORDER BY RAND()

To restrict each category to one, wrap the query in a partial GROUP BY:

SELECT * FROM (
    SELECT
    c.id AS cid, c.category, i.id AS iid, i.name
    FROM categories c
    INNER JOIN items i ON c.id = i.category
    ORDER BY RAND()
) AS shuffled_items
GROUP BY cid

Note that when a query has both GROUP BY and ORDER 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.

like image 138
Salman A Avatar answered Oct 25 '22 15:10

Salman A