如何使用子查询中的变量?

时间:2009-09-11 13:43:06

标签: sql mysql subquery

我有这个问题:

(SELECT e.IdEvent,e.EventName,e.EventSubtitle,e.EventDescription,l.LocationName,e.EventVenue,EventStartDate,e.EventEndDate,e.EventHost,c.CategoryName,l.LocationCity,l.LocationState,e.isTBA,
(SELECT s.status FROM jos_rsevents_subscriptions s WHERE s.IdUser = 72 AND s.IdEvent = e.IdEvent LIMIT 1) as status 
FROM jos_rsevents_events e 
    LEFT JOIN jos_rsevents_locations l ON e.IdLocation=l.IdLocation 
    LEFT JOIN jos_rsevents_categories c ON e.IdCategory=c.IdCategory 
WHERE 1=1  AND status < 3 ) ORDER BY  EventStartDate

但是我得到了错误。 “where子句”中的“未知列'状态'

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

尝试使用HAVING代替,因为在运行子查询后应用{...}:

(SELECT e.IdEvent,e.EventName,e.EventSubtitle,e.EventDescription,l.LocationName,e.EventVenue,EventStartDate,e.EventEndDate,e.EventHost,c.CategoryName,l.LocationCity,l.LocationState,e.isTBA,
(SELECT s.status FROM jos_rsevents_subscriptions s WHERE s.IdUser = 72 AND s.IdEvent = e.IdEvent LIMIT 1) as status 
FROM jos_rsevents_events e 
    LEFT JOIN jos_rsevents_locations l ON e.IdLocation=l.IdLocation 
    LEFT JOIN jos_rsevents_categories c ON e.IdCategory=c.IdCategory 
HAVING status < 3 ) ORDER BY  EventStartDate

答案 1 :(得分:0)

如果表jos_rsevents_subscriptions有主键,您也可以这样做:

 SELECT e.IdEvent, e.EventName, e.EventSubtitle, e.EventDescription, 
     l.LocationName, e.EventVenue, EventStartDate, e.EventEndDate, 
     e.EventHost, c.CategoryName, l.LocationCity, l.LocationState, e.isTBA, 
     s.status     
 FROM jos_rsevents_events e     
    LEFT JOIN jos_rsevents_locations l 
       ON e.IdLocation=l.IdLocation     
    LEFT JOIN jos_rsevents_categories c 
       ON e.IdCategory=c.IdCategory 
    Left Join jos_rsevents_subscriptions s 
       On s.PK = (Select Max(PK) From jos_rsevents_subscriptions
                  Where IdUser = 72 
                     AND IdEvent = e.IdEvent)
 WHERE 1=1 AND status < 3  
 ORDER BY EventStartDate

P.S。为什么1 = 1 ??