4

我有以下运行良好的 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

4

3 回答 3

2

WHERE子句在SELECT语句之前执行,因此它不知道新的别名places_availableMysql中操作的逻辑顺序是这样的:

  1. FROM 子句
  2. WHERE 子句
  3. GROUP BY 子句
  4. HAVING 子句
  5. 选择子句
  6. ORDER BY 子句

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

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-92JOIN语法而不是旧语法,并使用显式而不是像我所做的那样JOIN混合子句中的条件。WHERE

于 2013-09-04T09:47:41.413 回答
0

不能使用在查询中定义的别名,在WHERE子句中。为了使您的查询有效,请a.reg_limit-e.places_occupied>0WHERE子句中使用条件。

于 2013-09-04T09:46:44.130 回答
0

首先:另一个子句必须在第一次出现后由布尔逻辑运算符(ANDOR)添加WHERE。意思是:

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 对该查询的回答......不想在这里再次输入,也不想偷它;-)

于 2013-09-04T09:49:48.043 回答