MYSQL Select One Random record from each Category

后端 未结 4 359
星月不相逢
星月不相逢 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:17

    Here is a simple solution. Let suppose you have this table.

    id  name    category
    1   A       1
    2   B       1
    3   C       1
    4   D       2
    5   E       2
    6   F       2
    7   G       3
    8   H       3
    9   I       3
    

    Use this query

    select
      c.id,
      c.category,
      (select name from category where category = c.category   group by id order by rand() limit 1) as CatName
    from category as c
    group by category
    

提交回复
热议问题