如何做“喜欢X的用户也喜欢Y”查询?

时间:2013-10-13 04:11:26

标签: mysql sql algorithm

假设我有一个产品表,用户表,以及用户制作的产品的“喜欢”表。像这样:

create table likes (
user_id int unsigned not null,
product_id int unsigned not null,
rating set('like','dislike') not null,
primary key (user_id, product_id)
);

在特定产品的页面上,我想查询“赞”表,以查找喜欢此特定产品的用户“喜欢”的其他一些产品。这个查询会是什么样的?

2 个答案:

答案 0 :(得分:3)

您可以使用以下查询来查找也喜欢product_id=x的用户最喜欢的产品:

select L2.product_id, count(L2.user_id) as num_users from likes L1
join likes L2
where L1.product_id=x and L1.rating='like'
and L2.user_id = L1.user_id
group by L2.product_id
order by num_users desc;

答案 1 :(得分:1)

或者您可以使用内部查询来执行此操作

select l.product_id, count(u.user_id) as like_number
from (select user_id from likes where product_id=<product_id> and rating="like") as u
inner join likes as l on u.user_id=l.user_id
where l.rating="like"
group by l.product_id
having count(u.user_id) > <number>
order by like_number

有条款意味着只能建议超过一定数量用户喜欢的产品