我有两张 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/