使用内连接时的总和条件?

时间:2014-08-30 01:13:43

标签: mysql sql join

我有两张桌子:

a
idA User Size 
b
idB status name

User是从ab的外键。

此查询效果很好:

SELECT a.User,a.size,b.status,b.name, SUM(a.size) as TotalSize
FROM a
LEFT OUTER JOIN b
ON a.User=b.idB
WHERE a.size> 10
GROUP BY User
ORDER BY TotalSize DESC

但是当我试图在总和上设置一个条件时它失败了:

SELECT a.User,a.size,b.status,b.name, SUM(a.size) as TotalSize
FROM a
LEFT OUTER JOIN b
ON a.User=b.idB
WHERE TotalSize > 10  # or WHERE SUM(a.size)  > 10
GROUP BY User
ORDER BY TotalSize DESC

我该怎么办?

1 个答案:

答案 0 :(得分:1)

使用having子句(位于group by之后):

HAVING TotalSize > 10  # or HAVING SUM(a.size)  > 10

这是从聚合函数中过滤结果的正确方法。