我正在尝试写一个简单的'买了这个的顾客也买了......'
我有一个order
表,其中包含订单,还有一个order_product
表,其中包含与订单相关的所有产品。
为了找出使用product_id = 155
购买的五种最受欢迎的产品,我编写了以下查询:
select product_id, count(*) as cnt
from order_product
where product_id != 155
and order_id in
(select order_id from order_product where product_id = 155)
group by product_id
order by cnt desc
limit 5;
因此,内部查询获取了我感兴趣的产品(product_id = 155)的所有订单的列表,然后外部查询查找所有不同产品但属于同一产品的产品我的产品所在的订单。
然后订购它们并限制在前5名。
我认为这样可行,但需要很长时间 - 我想这是因为我使用的是一个包含几千个列表的IN。
我想知道是否有人能指出我以更优化的方式编写它的方向。
任何帮助都非常感激。
答案 0 :(得分:2)
您可以尝试更改此内容:
select p1.product_id, p1.count(*) as cnt
要
select p1.product_id, count(distinct p1.order_id) as cnt
看看是否会给你任何不同的结果
编辑: 来自评论
如果您希望在第一个查询中生成结果,可以尝试使用:
select a.product_id, count(*) as cnt
from order_product a
join (select distinct order_id from order_product where product_id = 155) b on (a.order_id = b.order_id)
where a.product_id != 155
group by a.product_id
order by cnt desc
limit 5;
对现有查询的一个小改动:)
答案 1 :(得分:1)
您可以尝试加入而不是子选择。类似的东西:
select p1.product_id, p1.count(*) as cnt
from order_product p1 JOIN order_product p2 on p1.order_id = p2. order_id
where p1.product_id != 155
and p2.product_id = 155
group by p1.product_id
order by p1.cnt desc
limit 5;