我想写一个简单的“顾客也买了.”
我有一个包含订单的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。
我想知道是否有人能以一种更优化的方式指出我写它的方向。
任何帮助都很感激。
发布于 2016-08-19 10:08:19
您可以尝试改变这种情况:
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;对现有查询的一个小改动:)
发布于 2016-08-19 09:33:12
您可以尝试一个联接,而不是一个子选择。类似于:
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;https://stackoverflow.com/questions/39035626
复制相似问题