【问题标题】:Find the most liked product from people who like a specific product in mysql从喜欢mysql中特定产品的人那里找到最喜欢的产品
【发布时间】:2014-10-19 20:39:56
【问题描述】:

Fiddle Example

我想知道如何使用下表架构从喜欢产品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

【问题讨论】:

  • 您可能只需要在group by 之后添加一个order by 语句。

标签: html mysql sql database


【解决方案1】:

如果你不关心领带,你可以使用:

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

小提琴: http://sqlfiddle.com/#!2/27d573/19/0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多