检索单个值及其总和?

1 mysql sql

我有一个表包含与另一个表相关的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
Run Code Online (Sandbox Code Playgroud)

这是stat表中的值:

stat_id, ip, ammount, link_id
1, 211.126.197.45, 10, 3 
2, 61.158.167.84, 7, 3 
Run Code Online (Sandbox Code Playgroud)

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

$total_ammount == 17;
$ips[0]['ammount'] == 10;
$ips[1]['ammount'] == 7;
Run Code Online (Sandbox Code Playgroud)

这样的事情......问题是查询是否正常还是可能更好(如何使其更好)?

Mar*_*ers 5

你可以使用GROUP BY ... WITH ROLLUP:

SELECT stat_id, SUM(ammount) AS amount
FROM stats
WHERE link_id = 3
GROUP BY stat_id WITH ROLLUP
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)