简体   繁体   English

MySql SUM 别名

[英]MySql SUM ALIAS

I have a problem with mysql alias.我的 mysql 别名有问题。

I have this query:我有这个查询:

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

My problem start from SUM , cannot recognize reservation and then i want to use the result for a where condition.我的问题从SUM开始, cannot recognize reservation ,然后我想将结果用于 where 条件。 Like ( where result > 10 )喜欢( where result > 10

To apply a predicate (filter condition) on the result of an aggregate function, you use a Having clause.要对聚合函数的结果应用谓词(过滤条件),请使用 Hading 子句。 Where clause expressions are only applicable to intermediate result sets created prior to any aggregation. 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

Not 100% but to the best of my knowledge you cant use aliases in your declarations, and thats why you are getting the column issue.不是 100%,但据我所知,您不能在声明中使用别名,这就是您遇到列问题的原因。 Try this:试试这个:

 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

One way is to wrap it into one more SELECT一种方法是将其包装成另一个 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


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM