MySql SUM ALIAS

时间:2013-06-08 17:19:46

标签: mysql sql sum alias

我的mysql别名有问题。

我有这个问题:

SELECT (`number_of_rooms`) AS total, id_room_type, 
     COUNT( fk_room_type ) AS reservation , 
     SUM(number_of_rooms - reservation) AS result
FROM room_type
    LEFT JOIN room_type_reservation 
         ON id_room_type = fk_room_type
WHERE  result > 10
GROUP BY id_room_type

我的问题从SUMcannot recognize reservation开始,然后我想将结果用于where条件。喜欢(where result > 10

3 个答案:

答案 0 :(得分:1)

要对聚合函数的结果应用谓词(过滤条件),请使用Having子句。 Where子句表达式仅适用于在任何聚合之前创建的中间结果集。

 SELECT (`number_of_rooms`) AS total, id_room_type,
     COUNT( fk_room_type ) AS reservation , 
     SUM(number_of_rooms - reservation) AS result
 FROM room_type
     LEFT JOIN room_type_reservation 
         ON id_room_type = fk_room_type
 GROUP BY id_room_type
 Having SUM(number_of_rooms - reservation) > 10

答案 1 :(得分:1)

不是100%但据我所知,您不能在声明中使用别名,这就是您遇到列问题的原因。试试这个:

 SELECT (`number_of_rooms`) AS total, id_room_type,
     COUNT( fk_room_type ) AS reservation , 
     SUM(number_of_rooms - COUNT( fk_room_type ) ) AS result
 FROM room_type
     LEFT JOIN room_type_reservation 
         ON id_room_type = fk_room_type
 GROUP BY id_room_type
 Having SUM(number_of_rooms - COUNT( fk_room_type ) ) > 10

答案 2 :(得分:0)

一种方法是将其包装成一个多 SELECT

SELECT t.*, t.number_of_rooms - t.reservation AS result FROM
  (
    SELECT (`number_of_rooms`) AS total, id_room_type, 
     COUNT( fk_room_type ) AS reservation , 
     SUM(number_of_rooms - reservation) AS result
     FROM room_type
     LEFT JOIN room_type_reservation 
         ON id_room_type = fk_room_type
     WHERE  result > 10
     GROUP BY id_room_type
   ) t