我想知道如何使用以下表架构找出喜欢该产品H135
的用户最喜欢的产品:
CREATE TABLE likes
(`user_id` int,`product_id`int)
;
INSERT INTO likes
(`user_id`,`product_id`)
VALUES
(1,22),
(1,44),
(2,33),
(2,44),
(3,22),
(3,55),
(4,44),
(4,11),
(5,22),
(5,44),
(5,33)
;
CREATE TABLE products
(`product_id` int,`product_name`varchar(30))
;
INSERT INTO products
(`product_id`,`product_name`)
VALUES
(11,'N570'),
(22,'KA89'),
(33,'A321'),
(44,'H135'),
(55,'C839')
;
预期输出应该是这样的
Liked_product users_who_like_it_also_like Result
H135 KA89 3
我尝试了self join
,但它没有产生任何结果:
SELECT p.product_name,p2.product_name AS other_liked_products,
COUNT(l2.product_id) AS users_who_like_it_also_like
FROM likes l
INNER JOIN products p ON p.product_id = l.product_id
INNER JOIN likes l2 ON l.product_id = l2.product_id
INNER JOIN products p2 ON p2.product_id = l2.product_id
WHERE l.product_id = 44
AND l2.product_id <> 44
GROUP BY l.product_id
LIMIT 1
答案 0 :(得分:2)
如果你不关心你可以使用的关系:
select 'H135' as liked_product,
p.product_name as users_who_like_it_also_like,
count(*) as result
from likes l
join products p
on p.product_id = l.product_id
where exists (select 1
from likes x
where x.user_id = l.user_id
and x.product_id = 44)
and l.product_id <> 44
group by p.product_name
order by 3 desc
limit 1
小提琴: http://sqlfiddle.com/#!2/27d573/17/0
在您的样本数据中,KA89的实际数量为2,并与A321相关联。
这将在一行的聚合列表中显示为与2的计数相关联:
select liked_product,
group_concat(users_who_like_it_also_like) as users_who_like_it_also_like,
result
from (select 'H135' as liked_product,
p.product_name as users_who_like_it_also_like,
count(*) as result
from likes l
join products p
on p.product_id = l.product_id
where exists (select 1
from likes x
where x.user_id = l.user_id
and x.product_id = 44)
and l.product_id <> 44
group by p.product_name) x
group by liked_product, result
order by result desc limit 1