2012-03-15 49 views
0

我试图根据用户的最爱提供艺术家建议。分组动作提供建议

我们的表看起来像:

USER_ID | artist_id
1 | 4
2 | 4
1 | 3
4 | 4
6 | 2
6 | 3
4 | 3
2 | 3

所以,如果一个随机的用户正在寻找artist_id 3,代码应该询问谁已经收藏artist_id 3其他用户的数据库,并找到它们之间的最常见的艺术家链接

在这种情况下,artist_id 3受用户1,3,4,6 ...以及那些用户的青睐,所以应该挑选出常见的artist_id 4(因为它看起来最多)。

那么我应该如何有效地做到这一点?

我会做几个查询吗?首先抓住所有拥有artist_id 3的user_id,然后抓取这些user_id的所有收藏夹并进行相应分组?

回答

2
SELECT t2.artist_id 
FROM tbl t1 
INNER JOIN tbl t2 
    ON t1.user_id = t2.user_id 
    AND t1.artist_id <> t2.artist_id 
WHERE t1.artist_id = 3 
GROUP BY t2.artist_id 
ORDER BY COUNT(*) DESC; 
+0

像一个魅力工作,谢谢你! – Mike 2012-03-15 21:06:03

1
SELECT * 
FROM TABLE A, 
(
    SELECT artist_id,user_id 
    FROM TABLE 
    WHERE artist_id=3 
    GROUP BY artist_id,user_id 
) B 
WHERE A.user_id=3 AND 
     A.user_id = B.artist_id; 
+0

你为什么加入到USER_ID artist_id?派生表是不必要的开销。 – nnichols 2012-03-15 20:53:15

0

我远离MySQL专家,但类似的东西可能工作。但是,对于mysql子查询来说这很棘手 - 当他们应用于大数据量时,他们倾向于做出疯狂的事情。

SELECT artist_id FROM `table` WHERE 
user_id IN (select user_id from `table` where artist_id = 3) 
and artist_id != 3 
group by artist_id 
order by count(artist_id) desc 
limit 1;