我有一个Items
表的数据库,看起来像这样:
id
name
category (int)
有几十万条记录。每个item
可以是7个不同的categories
之一,对应于categories
表:
id
category
我想要一个从每个类别中选择1个随机项的查询。什么是接近它的最佳方式?我知道使用Order By rand()
和LIMIT 1
进行类似的随机查询,但我从未做过类似的事情。
答案 0 :(得分:5)
此查询以随机顺序返回连接到类别的所有项目:
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()
要将每个类别限制为一个,请将查询包装在部分 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
请注意,当查询同时具有GROUP BY
和ORDER BY
子句时,将在排序之前执行分组。这就是为什么我使用了两个查询:第一个对结果进行排序,第二个对结果进行分组。
我知道这个查询不会赢得任何比赛。我愿意接受建议。
答案 1 :(得分:0)
请注意:在以下示例中,我假设您的表名为“items”而不是“Items”,因为您还说另一个表名为“categories”(第二个表名称未大写)。
您想要做的SQL大致是:
`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`
答案 2 :(得分:0)
试试这个
SELECT id, name, category from Items where
(
select count(*) from Items i where i.category = Items.category
GROUP BY i.category ORDER BY rand()
) <= 1
参考:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
答案 3 :(得分:0)
这是一个简单的解决方案。假设你有这张表。
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
使用此查询
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
答案 4 :(得分:0)
改变原表的顺序(随机顺序),最终选择前:
select * from
(select category, id, name from categories order by rand()) as tab
group by 1