简体   繁体   English

N:M MySQL关系中的DISTINCT和COUNT

[英]DISTINCT and COUNT in N:M MySQL relation

I have a N:M relation that connects customers and purchase Customer_id,Purchase_id . 我有一个N:M关系,可以连接客户并购买Customer_id,Purchase_id I would like to know how many purchases each specific user made, from one query. 我想从一个查询中了解每个特定用户进行了多少次购买。

I tried this: 我尝试了这个:

SELECT DISTINCT(Customer_id) AS ID,COUNT(Purchase_id) AS P FROM CustomerPruchases;

but it only gives me one row for the first customer in the DB. 但是对于数据库中的第一个客户,它只给我一行。 I want it for all. 我全都想要。

If you group then aggregate functions like count() apply to each group and not to the complete table 如果您进行分组,则诸如count()类的聚合函数将应用于每个组,而不是整个表

SELECT Customer_id as ID, 
       COUNT(Purchase_id) AS P_COUNT
FROM CustomerPruchases
group by ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM