计算包含Join的Query中的行

时间:2012-01-04 03:04:17

标签: mysql count

我的查询是这样的:

SELECT Product.local_price*Rate.exchange_rate AS 'US_price' FROM Product
 INNER JOIN Rate ON Rate.currency = Product.currency
 WHERE Product.type='TV'
 HAVING US_price BETWEEN 500 AND 600;

如何计算满足此查询的电视机数量?

表格结构

  • 产品表:ID,类型,local_price
  • 费率表:currency,exchange_rate

2 个答案:

答案 0 :(得分:2)

HAVING US_price替换为AND Product.local_price * Rate.exchange_rate,然后在COUNT(Product.ID)子句中执行SELECT

SELECT COUNT(Product.ID) 
FROM Product 
  INNER JOIN Rate ON Rate.currency = Product.currency 
WHERE Product.type='TV' 
  AND Product.local_price * Rate.exchange_rate BETWEEN 500 AND 600;

如果您需要汇总数据的标准,则需要使用HAVING,如下所示:

SELECT p.type, AVG(p.local_price)
FROM Product p
GROUP BY p.type
HAVING AVG(p.local_price) > 50

答案 1 :(得分:1)

此处无需使用HAVING条款;只有拥有GROUP BY子句时,它的特殊语义才有意义。因此,我们可以简单地将US_price子句中的HAVING替换为生成它的表达式,并将其移动到WHERE子句中;然后,使用SELECT COUNT(*)

SELECT COUNT(*)
  FROM Product
  JOIN Rate
    ON Rate.currency = Product.currency
 WHERE Product.type = 'TV'
   AND Product.US_price * Rate.exchange_rate BETWEEN 500 AND 600
;

此外,作为一般规则 - 在这种情况下不需要 - 您可以始终(或几乎总是?)将整个查询包装在SELECT COUNT(*) FROM (...) t中以获取它返回的总行数。