您可以使用 WHERE 子句中的相关子查询来执行此操作:
select b.name, c.id
from categories c join
business b
on c.business_id = b.id
where c.id in (select c2.id
from categories c2
where c2.business_id = c.business_id
order by rand()
limit 5
)
在其他支持排名功能的数据库中,这要简单得多。
如果此子查询不支持限制,那么您必须使用自联接来完成。咳咳咳咳:
with bc as (
select b.name, c.id
from categories c join
business b
on c.business_id = b.id
)
select bc.name, bc.id
from bc join
bc bcprev
on bc.name = bcprev.name and
bcprev.id <= bc.id
group by bc.name, bc.id
having count(*) <= 5
这不会得到 5 个随机类别。相反,它会获得 id 最低的五个。
罗斯史密斯编辑:
上面的查询在 MySQL 5.5.25 中返回错误,但下面的工作:
select bc.name, bc.id
from
(
select b.name, c.id
from categories c join
business b
on c.business_id = b.id
) bc join
(
select b.name, c.id
from categories c join
business b
on c.business_id = b.id
) bcprev
on bc.name = bcprev.name and
bcprev.id <= bc.id
group by bc.name, bc.id
having count(*) <= 5
并且似乎返回了这个预期的结果。
见http://sqlfiddle.com/#!2/ea78a/9