MYSQL Select One Random record from each Category

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

    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:

    `SELECT items.id AS item_id,
    items.name AS item_name,
    items.category AS item_category_id,
    categories.id AS category_id,
    categories.category AS category_name
    FROM items, category
    WHERE items.category = categories.id
    ORDER BY rand()
    LIMIT 1`
    

提交回复
热议问题