提问者:小点点

盘点一起购买的产品


我做了一个查询,计算有多少产品一起购买,但我不想有产品的两种方式在它

代码


DB::table(DB::raw('tenant_db.sales_data as b'))
            ->selectRaw('a.product_id as product_id, b.product_id as bought_with, count(*) as times_bought_together')
            ->join(DB::raw('tenant_db.sales_data as a'), function ($join){
                $join->on('a.sale_id', '=', 'b.sale_id');
                $join->on('a.product_id', '!=', 'b.product_id');
            })
            ->groupBy('a.product_id', 'b.product_id');

输出

Product_id          Bought_with         times_bought_together'

52                      24                          3
24                      52                          3

所以我只想拥有一次而不是两次,那可能吗(基于数量)?


共1个答案

匿名用户

使用<而不是!=:

$join->on('a.product_id', '<', 'b.product_id');