我有3张这样的表
soft_id soft_name
1 Office
pu_id soft_id pu_quantity
1 1 10
2 1 20
3 1 30
own_id soft_id owner
1 1 Peter
2 1 Tommy
3 1 David
如何在一个单独的mysql查询中得到这样的结果
soft_id soft_name sum(pu_quantity) count(owner)
1 Office 60 3
答案 0 :(得分:0)
试试这个
SELECT S.soft_id,S.soft_name,P.sum(pu_quantity),O.count(owner)
FROM Soft S INNER JOIN Product P ON S.soft_id = P.soft_id
Inner JOIN Owner O = P.soft_id = O.soft_id
Group By S.soft_id,P.soft_id,O.soft_id,S.soft_name
答案 1 :(得分:0)
试试这个:
SELECT a.soft_id,
a.soft_name,
b.p_cnt AS quantity,
c.o_cnt AS owner_count
FROM soft a
INNER JOIN
(SELECT soft_id, SUM(pu_quantity) AS p_cnt FROM product GROUP BY soft_id
) b
ON a.soft_id = b.soft_id
INNER JOIN
(SELECT soft_id, COUNT(*) AS o_cnt FROM owner GROUP BY soft_id
) c
ON b.soft_id = c.soft_id
GROUP BY a.soft_id,
a.soft_name
注意:假设表名分别是软,产品和所有者。