在MYSQL中按多列的总和进行搜索

时间:2013-12-05 21:33:53

标签: mysql

我有一个关于属性的数据表,包括按1/4浴,1/2浴,3/4浴和浴室分解的浴室。全浴,但我希望人们能够通过总浴(四种浴的总和)搜索。我已经提出了这个有效但看起来不优雅的查询。有更干净/更好的方法吗?具体来说,我试图在where子句中使用TotalBaths,但它没有用。我正在使用coalesce,因为有时值为NULL。如果此人搜索2或3个浴室,则为此示例。

SELECT *, 
         COALESCE(FullBathrooms,0)+ 
         COALESCE(HalfBathrooms,0)+ 
         COALESCE(OneQuarterBaths,0)+
         COALESCE(ThreeQuarterBaths,0) as TotalBaths 

FROM properties 
WHERE ( COALESCE(FullBathrooms,0)+
        COALESCE(HalfBathrooms,0)+
        COALESCE(OneQuarterBaths,0)+
        COALESCE(ThreeQuarterBaths,0) BETWEEN 2 AND 3 
       ) 
ORDER BY Price DESC LIMIT 10 OFFSET 0

1 个答案:

答案 0 :(得分:3)

在MySQL中,您可以使用having表达式而不是wherehaving子句允许您使用列别名:

SELECT *,
       (COALESCE(FullBathrooms,0) + COALESCE(HalfBathrooms,0) + 
        COALESCE(OneQuarterBaths,0)+ COALESCE(ThreeQuarterBaths,0)
       ) as TotalBaths
FROM properties
HAVING TotalBaths between 2 and 3
ORDER BY Price DESC
LIMIT 10 OFFSET 0;

您也可以使用子查询来执行此操作 - 但这可能无法执行,因为子查询可能已实现:

select p.*
from (select p.*,
             (COALESCE(FullBathrooms,0) + COALESCE(HalfBathrooms,0) + 
              COALESCE(OneQuarterBaths,0)+ COALESCE(ThreeQuarterBaths,0)
             ) as TotalBaths
      from properties p
     ) p
where TotalBaths between 2 and 3
ORDER BY Price DESC
LIMIT 10 OFFSET 0;

这是在大多数其他SQL引擎中简化此查询的方式(嗯,子查询或CTE)。