php - Mysql 限制列值重复N次

标签 php mysql group-by

我有两张 table

Customer (idCustomer, ecc.. ecc..)
Comment (idCustomer, idComment, ecc.. ecc..)

显然这两个表是连在一起的,例如

SELECT * FROM Comment AS co
  JOIN Customer AS cu ON cu.idCustomer = co.idCustomer

有了这个,我从与客户相关联的表中选择所有评论,但现在我想限制评论的数量,每个客户最多 2 个评论。

我看到的第一件事是使用 GROUP BY cu.idCustomer 但它只限制每个客户 1 条评论,但我想每个客户 2 条评论。

我怎样才能做到这一点?

最佳答案

MySQL 中的一个选项是服务器端变量。例如:

set @num := 0, @customer := -1;

select  *
from    (
        select  idCustomer
        ,       commentText
        ,       @num := if(@customer = idCustomer, @num + 1, 1) 
                    as row_number
        ,       @customer := idCustomer
        from    Comments
        order by 
                idCustomer, PostDate desc
        ) as co
join    Customer cu
on      co.idCustomer = cu.idCustomer
where   co.row_number <= 2

关于php - Mysql 限制列值重复N次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038009/

相关文章:

php - 如何对数据库中的数据进行分组

sql - Oracle SQL 选择不在 GROUP BY 子句中的行

sql - 每 15 分钟高效地查询一个巨大的时间序列表一行

php - 安装了 Memcached(理论上),PHP 无法使用 memcache_connect()

php - 使用 crypt() 对数据库进行哈希处理后 PHP 登录脚本出现问题

php - strtotime(PHP 日期函数)的算法如何工作?

mysql - 如何以编程方式在 MySQL 中设置 max_connections

php - Laravel 5.3 失败时自动连接到另一个数据库

php - 为什么 mysqli_num_rows 总是返回 0?

mysql - 通过和枢轴加入一个组