关于两列MySQL之间的减法的WHERE子句

时间:2013-09-04 09:43:16

标签: mysql sql where

我有以下MySQL查询运行绝对正常:

SELECT a.id, a.event_name, c.name, a.reg_limit-e.places_occupied AS places_available, a.start_date
FROM nbs_events_detail AS a, nbs_events_venue_rel AS b, nbs_events_venue AS c,
(SELECT e.id, COUNT(d.event_id) AS places_occupied FROM nbs_events_detail AS e LEFT JOIN nbs_events_attendee AS d ON e.id=d.event_id GROUP BY e.id) AS e
WHERE a.id=b.event_id AND b.venue_id=c.id AND a.id=e.id AND a.event_status='A' AND a.start_date>=NOW()
ORDER BY a.start_date

但是,我尝试添加一个WHERE子句,以便过滤为减法创建的列中显示的结果:a.reg_limit-e.places_occupied AS places_available

到目前为止我所做的是添加如下WHERE条款: WHERE places_available>0

但是,如果我尝试使用此指令,查询将失败,并且不会显示任何结果。报告的错误如下:#1054 - Unknown column 'places_available' in 'where clause'

a.reg_limit我有号码,e.places_occupied我的子查询中COUNT生成了数字。
我错过了什么?

3 个答案:

答案 0 :(得分:2)

WHERE子句在SELECT语句之前执行,因此它不知道新的别名places_availablethe logical order of operations in Mysql是这样的:

  
      
  1. FROM clause
  2.   
  3. WHERE子句
  4.   
  5. GROUP BY子句
  6.   
  7. HAVING条款
  8.   
  9. SELECT条款
  10.   
  11. ORDER BY子句
  12.   

作为解决方法,您可以将其包装在这样的子查询中:

SELECT *
FROM
(
    SELECT 
      a.id, 
      a.event_name, 
      c.name, 
      a.reg_limit-e.places_occupied AS places_available,  
      a.start_date
    FROM nbs_events_detail AS a
    INNER JOIN nbs_events_venue_rel AS b ON a.id=b.event_id
    INNER JOIN nbs_events_venue AS c ON b.venue_id=c.id 
    INNER JOIN
    (
       SELECT e.id, 
         COUNT(d.event_id) AS places_occupied 
       FROM nbs_events_detail AS e 
       LEFT JOIN nbs_events_attendee AS d ON e.id=d.event_id    GROUP BY e.id
    ) AS e ON a.id=e.id
    WHERE a.event_status='A' AND a.start_date>=NOW()
) AS t
WHERE places_available>0
ORDER BY a.start_date;

还尝试使用ANSI-92 JOIN语法而不是旧语法,并使用显式JOIN而不是像我所做的那样混合WHERE子句中的条件。

答案 1 :(得分:0)

can not use aliases,在查询中定义,位于WHERE子句中。为了使您的查询有效,请在a.reg_limit-e.places_occupied>0子句中使用条件WHERE

答案 2 :(得分:0)

首先:在第一次AND出现后,必须通过布尔逻辑运算符(ORWHERE)添加另一个子句。 含义如下:

SELECT * FROM yourtable
WHERE col1 = value
AND col2 = value

第二:你在你的减法上放了一个别名,但是你不会按照你想要的方式在WHERE子句中使用。 你可以这样写(我的坏/坏建议):

SELECT a.id, a.event_name, c.name, a.reg_limit-e.places_occupied AS places_available, a.start_date
FROM nbs_events_detail AS a, nbs_events_venue_rel AS b, nbs_events_venue AS c,
(SELECT e.id, COUNT(d.event_id) AS places_occupied FROM nbs_events_detail AS e LEFT JOIN nbs_events_attendee AS d ON e.id=d.event_id GROUP BY e.id) AS e
WHERE a.id=b.event_id 
AND b.venue_id=c.id 
AND a.id=e.id 
AND a.event_status='A' 
AND a.start_date>=NOW()
AND a.reg_limit-e.places_occupied > 0
ORDER BY a.start_date

或者您可以使用子查询 - 这将是更好的表现...因为WHERE子句中的函数方程式是邪恶的和性价比。请参阅Mahmoud Gamals对该查询的回答...不要再在这里输入它,也不想偷它; - )