我的数据如下:
表是:order_details(order_id int not null,prod_id int not null)
Order_id Prod_id
1 1
1 2
2 3
3 4
4 1
4 2
4 7
我需要找到两个或更多产品的组合,这些产品在订单中一起出售 对于此数据,这将是产品1和2,因为这些数据针对单个订单发生两次。 我需要为大多数订单一起出现的产品以及它们一起出现的订单数量。
我正在使用此查询:
select distinct od1.prod_id,od2.prod_id from order_details od1 join order_details od2 on od1.order_id=od2.order_id where od1.prod_id!= od2.prod_id limit 10;
这仅适用于2种产品的组合,不计算在内。
这可以做得更好吗?
谢谢!
答案 0 :(得分:0)
ariaDB [sandbox]> drop table if exists t;
Query OK, 0 rows affected (0.10 sec)
MariaDB [sandbox]> create table t (Order_id int,Prod_id int);
Query OK, 0 rows affected (0.19 sec)
MariaDB [sandbox]> insert into t values
-> (1 , 1),
-> (1 , 2),
-> (2 , 3),
-> (3 , 4),
-> (4 , 1),
-> (4 , 2),
-> (4 , 7),
-> (5 , 1),
-> (5 , 2),
-> (6 , 1),
-> (6 , 2),
-> (6 , 7),
-> (7 , 1),
-> (7 , 2),
-> (7 , 7),
-> (8 , 7),
-> (8 , 2)
-> ;
Query OK, 17 rows affected (0.07 sec)
Records: 17 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> select s.prodmix,count(*) Obs
-> from
-> (
-> select order_id,
-> group_concat(prod_id order by prod_id asc) prodmix, count(*) as obs
-> from t
-> group by order_id
-> having count(*) > 1
-> ) s
-> group by prodmix
-> order by obs desc limit 2;
+---------+-----+
| prodmix | Obs |
+---------+-----+
| 1,2,7 | 3 |
| 1,2 | 2 |
+---------+-----+
2 rows in set (0.04 sec)