如何让用户获得大多数产品

时间:2016-09-04 07:24:21

标签: mysql sql

我有3张桌子:

发票:

invoice_id | user_name | user_id | cost | shop_Id 

发票产品:

id | invoice_id | user_id | product_id | quantity

产物:

product_id | product_name | description

我需要前5位客户,其中shop_id = 1结果&客户有多种产品:

invoice_id | user_name | user_id | product_name | product_description

1 个答案:

答案 0 :(得分:0)

您可以按照以下步骤操作 - 加入表格,计算产品数量,按计数排序并使用LIMIT

SELECT i.user_name,count(p.product_id) as cnt_products 
FROM invoice i
JOIN invoice_products ip
 ON(i.invoice_id = ip.invoice_id)
JOIN product p
 ON(p.product_id = ip.product_id)
WHERE i.shop_id = 1
GROUP BY i.user_name 
ORDER BY cnt_products DESC
LIMIT 5