php - MySQL 按类别分组,每个类别限制 N 个

标签 php mysql

表格

id       title        category
<小时/>
1        hello1          1
2        hello2          2
3        hello3          1

查询

select  *
from    videos
where   category in
        (
        select  category
        from    videos
        group by 
               category
        having 
               count(*) < 3
ORDER BY RAND()
        )

我的目标是以随机顺序从每个类别中获得 2 个标题 我也想以这种方式获取记录

category1
title1
title2
<小时/>
category2
title1
title2

最佳答案

以下查询给出每个类别中不超过两个随机行:

SELECT title, category
FROM (
  SELECT v.*,
     if( category = @last_cat,
         if( @last_cat:=category, @x:=@x+1,@x:=@x+1),
         if( @last_cat:=category, @x:=0,@x:=0)
     ) x
  FROM (SELECT @last_cat:=-9876, @x:=-91234) x,
       (SELECT * FROM videos ORDER BY category, rand()) v
) x
WHERE x < 2

演示:http://sqlfiddle.com/#!2/59cf9/8

关于php - MySQL 按类别分组,每个类别限制 N 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27752407/

相关文章:

javascript不调用php变量

mysql - 如何在查询中合并?

java - 错误 :java. sql.SQLException:用户 'root@localhost' @'localhost' 的访问被拒绝(使用密码:YES)

php - 带有限制和偏移量的 CodeIgniter sql 查询不显示结果

javascript - 如何在 Chrome 扩展中使用 javascript 发出 POST 请求?

php - 向用户显示年龄检查表,而不是机器人 - SEO 安全吗?

MySQL - 每个类别 5 个帖子

mysql - 基本 SQL 触发器

Windows 7 64 位和 Apache 下的 PHP 和 CURL

javascript - MongoDB (php) - 将文档属性作为数组而不是多个属性返回