我有2张桌子。
表1:水果 id(int,autoincreasing,primary key) 其他一些垃圾
表2:客户 有一个'fruit'列,此列包含fruit table中的id。
我想查询所有客户,并提供所有水果ID及其使用次数的列表。
所以这个设置: 水果已经
id name
1 orange
2 banana
3 apple
客户有6行,如:
id fruit
1 1
2 1
3 2
4 2
5 2
6 3
尝试编写一个会给我的查询:
fruit id purchase count
1 2
2 4
3 1
答案 0 :(得分:1)
试试这个
SELECT f.id as fruit_id, COUNT(1) AS purchase_count
FROM FRUITS f LEFT JOIN CUSTOMERS c
ON F.ID = c.fruit
GROUP BY f.id
答案 1 :(得分:0)
应该只是一个简单的聚合......
SELECT fruit_id, COUNT(fruit_id) AS purchase_count
FROM customers
GROUP BY fruit_id
ORDER BY fruit_id ASC;
答案 2 :(得分:0)
未测试
SELECT id, SUM(fruit) as "fruit id", "purchase count"
FROM Customers
GROUP BY id;