根据客户购买的产品过滤客户
Filter customers based on products they bought
我有 3 个 table:
- 客户(主键:customer_id)
- customer_order(PK:order_id,FK:customer_id,product_id)
- 产品(PK:product_id)
一行 customer_order 包含一位客户和该客户在该订单中购买的产品。
现在做一个管理系统,我要输入一个产品列表,找到一个购买了所有这些产品(含)的客户列表。我所说的包容性是指所有被过滤的客户必须购买所有产品。
注意事项:
- 每位退货的顾客可能购买了更多的产品。 (输入的产品列表可能是一个子集)
- 作为输入发送的产品数量可能会有所不同
- 我正在尝试用 JPQL 编写。
在 mysql 我在 customer_order table 中使用类似的东西:
select customer_id from (SELECT count(distinct (product_id)) as prodcount, customer_id FROM customer_order where product_id = :prod_id1 or product_id = :prod_id2 group by customer_id) as temp where temp.prodcount= 2;
这里product_id的个数是可变的:prod_id1、prod_id2、prod_id3等。在 temp.prodcount= 2
中,'2' 是作为输入的产品数量。
在按输入产品列表(where 子句)过滤订单后,我正在计算客户从 customer_order table 购买的不同产品数量。然后将计数与输入的产品数量进行比较。如果它们相等,则表示这是购买了输入的所有产品的客户
我不确定这是正确的做法,因为它看起来更像是一种 hack。此外,我需要用 JPQL 编写。因此,JPQL 解决方案会有所帮助。
您的方法很好,但您可以通过删除子查询并使用 in
:
来简化查询
select co.customer_id
from customer_order co
where co.product_id in (:prod_id1, :prod_id2)
group by co.customer_id
having count(distinct product_id) = 2;
我有 3 个 table:
- 客户(主键:customer_id)
- customer_order(PK:order_id,FK:customer_id,product_id)
- 产品(PK:product_id)
一行 customer_order 包含一位客户和该客户在该订单中购买的产品。
现在做一个管理系统,我要输入一个产品列表,找到一个购买了所有这些产品(含)的客户列表。我所说的包容性是指所有被过滤的客户必须购买所有产品。
注意事项:
- 每位退货的顾客可能购买了更多的产品。 (输入的产品列表可能是一个子集)
- 作为输入发送的产品数量可能会有所不同
- 我正在尝试用 JPQL 编写。
在 mysql 我在 customer_order table 中使用类似的东西:
select customer_id from (SELECT count(distinct (product_id)) as prodcount, customer_id FROM customer_order where product_id = :prod_id1 or product_id = :prod_id2 group by customer_id) as temp where temp.prodcount= 2;
这里product_id的个数是可变的:prod_id1、prod_id2、prod_id3等。在 temp.prodcount= 2
中,'2' 是作为输入的产品数量。
在按输入产品列表(where 子句)过滤订单后,我正在计算客户从 customer_order table 购买的不同产品数量。然后将计数与输入的产品数量进行比较。如果它们相等,则表示这是购买了输入的所有产品的客户
我不确定这是正确的做法,因为它看起来更像是一种 hack。此外,我需要用 JPQL 编写。因此,JPQL 解决方案会有所帮助。
您的方法很好,但您可以通过删除子查询并使用 in
:
select co.customer_id
from customer_order co
where co.product_id in (:prod_id1, :prod_id2)
group by co.customer_id
having count(distinct product_id) = 2;