MySQL 获取产品也购买了产品/优化 IN 查询

MySQL Get products also bought with a product / Optimise IN query

我想写一个简单的'customers who bought this also bought...'

我有一个 order table,其中包含订单,还有一个 order_product table,其中包含与订单相关的所有产品。

为了找出使用 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 和几千个列表。

我想知道是否有人可以指出我以更优化的方式编写它的方向。

非常感谢任何帮助。

您可以尝试使用联接而不是子选择。类似于:

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;

您可以尝试更改此设置:

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;

对您现有查询的小改动 :)