我需要编写一个MySQL查询,它给出了有关已定义用户的统计信息。让我们说我需要销售,他加入的团体数量以及他得到的朋友数量。
SELECT SUM( sells.qtty ) sells,
SUM( sells.price ) total,
COUNT( DISTINCT groups.id ) groupsTotal,
COUNT( DISTINCT friends.id ) friendsTotal
FROM members
LEFT JOIN sells
ON sells.idmember = members.id
LEFT JOIN groups
ON groups.idmember = members.id
LEFT JOIN friends
ON friends.idmember = members.id
where members.id = 3
让我们说这给了我40个团体和20个朋友。我不能在售卖表格的ID列上使用不同的。因此,总和给了我疯狂的销售量(如果真实的话会很好,但在尝试显示统计数据时则不然。)
我在这里非常困惑......如果有任何帮助,请提前感谢!
答案 0 :(得分:2)
您需要在加入之前进行聚合。一种方法是在from
子句中使用子查询:
select s.sells, s.total, g.groupsTotal, f.friendsTotal
from members m left outer join
(select s.idmember, sum(s.qtty) as sells, sum(s.price) as total
from sells s
where s.idmember = 3
) s
ON s.idmember = m.id left outer join
(select g.idmember, count(*) as groupstotal
from groups g
where g.idmember = 3
) g
on g.idmember = m.id left outer join
(select f.idmember, count(*) as friendstotal
from friends
where f.idmember = 3
) f
on f.idmember = m.id
where m.id = 3;
通常,子查询中的where
子句将改为group by
。但是您只选择一个成员,因此在每个子查询中过滤效率更高。