检索单个值及其总和?

时间:2010-10-17 13:12:02

标签: sql mysql

我有一个包含与另一个表相关的link_ids的表;此表的标题为ammount的列存储了类型为int的值。为了检索一些总数与单个值,我查询如下:

SELECT ip, ammount, (SELECT SUM(ammount) FROM stats WHERE link_id = $link_id) as total_ammount FROM stats WHERE link_id = $link_id

这是统计表中的值:

stat_id, ip, ammount, link_id
1, 211.126.197.45, 10, 3 
2, 61.158.167.84, 7, 3 

所以,我需要检索link_id的总ammount以及它的各个ammounts:

$total_ammount == 17;
$ips[0]['ammount'] == 10;
$ips[1]['ammount'] == 7;

类似的东西......问题是查询是否正常还是可能更好(如何使其更好)?

1 个答案:

答案 0 :(得分:5)

您可以使用GROUP BY ... WITH ROLLUP

SELECT stat_id, SUM(ammount) AS amount
FROM stats
WHERE link_id = 3
GROUP BY stat_id WITH ROLLUP

结果:

stat_id  amount
1,       10    
2,       7     
NULL,    17    

或者您可以使用UNION ALL

SELECT stat_id, ammount AS amount
FROM stats
WHERE link_id = 3

UNION ALL

SELECT NULL, SUM(ammount)
FROM stats
WHERE link_id = 3