以下查询正常:
SELECT user.username, preference.user_id, preference.category,COUNT(*) AS occurrences
FROM preference inner
JOIN user on preference.user_id=user.userid
where category is not null and category!=""
GROUP BY category,user_id
ORDER BY occurrences DESC ;
我想要
A)只获得每个用户名的最受欢迎的类别(具有最大出现次数的用户名),因此对于user1的上述小提琴,它将是服装,鞋子&附件(3次出现)和用户2古董(3次出现),除了这两个之外的所有其他行都应该省略。
B)另一个查询,以获得每个用户名的第二个最受欢迎的类别
答案 0 :(得分:2)
您可以使用变量仅为每个用户选择2个最受欢迎的类别
SELECT * FROM (
SELECT * ,
@rowNum := IF(@prevUserId = user_id,@rowNum+1,1) rowNum,
@prevUserId := user_id
FROM (
SELECT user.username,@prevUserId,preference.user_id, category, COUNT(*) AS occurrences
FROM preference inner JOIN user
on preference.user_id=user.userid
where category is not null and category!=""
GROUP BY category,preference.user_id
) t1 order by user_id, occurrences desc
) t1 WHERE rowNum <= 2