1

我需要从数据库中显示一组可用房间的结果,其中条件是:

  1. alm_num = 1
  2. alm_date 2012 年 11 月 26 日至 29 日之间
  3. 和 sum_num > or = 3

然后我像这样编写mySQL:

select sum(villas_allotment.alm_num) as sum_num, 
villas_allotment.alm_id as aid, villas_db.v_name as vname  
from villas_allotment 
inner join villas_db on villas_allotment.alm_vid=villas_db.v_id 
where alm_num='1' 
and alm_date between '2012-11-26' and '2012-11-29' 
and alm_vid='3' 
and sum_num>='3'

但我有:

#1054 - Unknown column 'sum_num' in 'where clause'

那么你们能否建议我如何从这个错误中生存下来。问候,

4

1 回答 1

3

您需要HAVING在聚合列上使用 for 条件:

select
    sum(villas_allotment.alm_num) as sum_num, 
    villas_allotment.alm_id as aid,
    villas_db.v_name as vname  
from villas_allotment 
inner join villas_db on villas_allotment.alm_vid = villas_db.v_id 
where alm_num = '1' 
and alm_date between '2012-11-26' and '2012-11-29' 
and alm_vid = '3' 
group by villas_allotment.alm_id, villas_db.v_name
having sum(villas_allotment.alm_num) >= 3

您还需要group by关于非聚合列的子句,我为您添加了该子句。

于 2012-11-22T19:36:05.133 回答