Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL Get products还与product/Optimize一起购买_Mysql_Sql_Opencart_Query Optimization - Fatal编程技术网

MySQL Get products还与product/Optimize一起购买

MySQL Get products还与product/Optimize一起购买,mysql,sql,opencart,query-optimization,Mysql,Sql,Opencart,Query Optimization,我试图写一个简单的“买了这个的顾客也买了…” 我有一个订单表,其中包含订单,还有一个订单产品表,其中包含与订单相关的所有产品 为了找出使用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 prod

我试图写一个简单的“买了这个的顾客也买了…”

我有一个订单表,其中包含订单,还有一个订单产品表,其中包含与订单相关的所有产品

为了找出使用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;
因此,内部查询将获取所有订单的列表,这些订单中包含我感兴趣的产品。\u id=155,然后外部查询将查找所有不属于同一产品但属于我的产品所在订单的产品

然后订购并限制在前5位

我认为这很好用,但需要很长时间——我想这是因为我在使用一个有几千个的列表

我想知道是否有人能给我指出一个更优化的写作方向


非常感谢您的帮助。

您可以尝试加入,而不是子选择。比如:

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 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;

对现有查询的一个小改动:

使用不带前缀的count*有效,但会给我的原始查询提供不同的结果手动检查这两个查询-哪一个具有正确的计数?如果需要产品“namex”,然后使用Product_id从Diego的查询中选择名称作为x连接产品。是的,这会给出不同的结果。事实上,所有3个都是不同的,通过做一些测试,似乎在您的案例中,count*给出了给定产品的编号中有多少是与产品155一起订购的。而countdistinct p1.order_id则提供给定产品的订单数量,该产品id与产品155的订单数量相同。如果这有任何意义的话?是的,我认为这是有意义的,但是,我希望他们中的一个能给出与我最初的查询相同的结果,但两者都不能!?我之前的陈述可能有点错误。根据我的理解,经过更多的研究。您的第一个查询:统计与155关联的所有产品,无论其订单是否相同,也就是说,产品111在订单1中与155一起订购了三次,您的查询将此计算为三次。count*会计算与155关联的所有产品以及由联接导致的任何重复产品,countdistinct order_id会计算该产品与155关联的唯一订单数。如果查询仍然需要时间,请告诉我:您是否曾经在一个订单中拥有相同的产品_id两次?如果是这样的话,答案必须更加努力。这一点很好,但不是-如果订单中添加了相同id的产品,那么数量字段应该增加,而不是添加另一条记录。
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;