我有两张桌子
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,group-by
来源: https://codeday.me/bug/20190730/1582236.html