我有两张桌子
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条评论。
我怎样才能做到这一点?
答案 0 :(得分:3)
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
答案 1 :(得分:2)
此版本不需要SET操作:
select *
from (select idCustomer
, commentText
, @num := if(@customer = idCustomer, @num + 1, 1) as row_number
, @customer = idCustomer
from Comments
JOIN(SELECT @num := 0, @customer := 1) r
order by idCustomer, PostDate desc) as co
join Customer cu on co.idCustomer = cu.idCustomer
where co.row_number <= 2
答案 2 :(得分:2)
SELECT * FROM Comments AS cm1
LEFT JOIN Comments AS cm2 ON cm1.idCustomer = cm2.idCustomer
LEFT JOIN Customer AS cu ON cm1.idCustomer = cu.idCustomer
WHERE cm1.idComment != cm2.idComment
GROUP BY cm1.idCustomer
但是,如果您要更改评论数量,最好使用Andomar的解决方案。
答案 3 :(得分:0)
没有必要使用光标,这非常慢。请参阅我对Complicated SQL Query About Joining And Limitting的回答。 DENSE_RANK将在没有所有游标错综复杂的情况下完成这项工作。
答案 4 :(得分:0)
如果您使用PHP等脚本语言来处理结果,则可以在运行查询后限制每个客户显示的结果数。设置一个数组来保存所有结果,设置另一个数组来保存每个客户的结果数,并在计数超过限制后停止将查询结果添加到结果集中,如下所示:
$RESULTS = array();
$COUNTS = array();
$limit = 2;
$query = "SELECT customer_id, customer_name, customer_comment FROM customers ORDER BY RAND()";
$request = mysql_query($query);
while ($ROW = mysql_fetch_assoc($request))
{
$c = $ROW['customer_id'];
$n = $COUNTS[$c];
if ($n<$limit)
{
$RESULTS[] = $ROW;
$COUNTS[$c]++;
}
}
这样可以保证每个客户只会随机显示两条评论或者您想要的,其余的评论会被抛弃。当然,你要提取所有结果,但这比(进行复杂连接)要快得多。