MYSQL Select One Random record from each Category

后端 未结 4 352
星月不相逢
星月不相逢 2020-12-10 07:30

I have a database with an Items table that looks something like this:

id
name
category (int)

There are several hundred thousan

4条回答
  •  暖寄归人
    2020-12-10 08:27

    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.

提交回复
热议问题