2017-03-14 196 views
0

我想將PHP $where作爲大查詢的一部分。我需要這樣的東西:SELECT * FROM表WHERE`id` in ...和where sum()less

SELECT * 
    FROM rf2aq_eb_events 
WHERE id 
    IN (SELECT event_id 
       , SUM(number_registrants) summ 
      FROM rf2aq_eb_registrants 
      WHERE summ < event_capacity 
     ); 

rf2aq_eb_events表如下所示:

ID | event_capacity 

1 | 7 
2 | 5 
3 | 9 

rf2aq_eb_registrants表:

ID | events_id | number_registrants 

1 | 1   | 6  
2 | 2   | 2 
3 | 3   | 4 
4 | 1   | 1  
5 | 2   | 0 
6 | 3   | 5  

我需要用的量事件 'rf2aq_eb_events' select事件註冊人<然後event_capacity。有event id = 2迴應條件。

我試過$where[] = 'a.id IN (SELECT event_id FROM #__eb_registrants GROUP BY event_id HAVING sum(number_registrants) < a.event_capacity)';

它的工作像SQL,但在整個查詢PHP沒有。

下面我把php結果。

SELECT a.id, a.title, a.location_id, 
     a.event_capacity, a.event_date, a.individual_price, 
     a.thumb, a.early_bird_discount_date, a.early_bird_discount_amount, 
     c.name AS location_name 
FROM #__eb_events AS a 
     LEFT JOIN #__eb_locations AS c 
     ON a.location_id = c.id 
WHERE a.published =1 
     AND DATE(event_date) between date(CURDATE() + INTERVAL 7 DAY) 
     and date(CURDATE() + INTERVAL 26 DAY) 
     AND (
     cut_off_date = "0000-00-00 00:00:00" 
     OR DATE(cut_off_date) between NOW() and date(CURDATE() + INTERVAL 26 DAY) 
    ) AND a.id IN ( 
      SELECT event_id 
      FROM #__eb_registrants 
      GROUP BY event_id 
      HAVING sum(number_registrants) < a.event_capacity 
    ) AND a.id IN (
      SELECT event_id FROM #__eb_event_categories 
      WHERE category_id IN (6,7) 
    ) AND a.access IN (1,1) 
ORDER BY a.event_date 
LIMIT 4 
+1

該示例查詢將無法正常工作,但是對問題預期結果將會很好。 –

+0

我發現了錯誤。剛剛從select中刪除a.event_capacity。 –

回答

0

不能使用的骨料在WHERE的結果(例如SUM),你可以在HAVING使用它,但你需要在這種情況下做了GROUP BY還有:

SELECT * FROM `rf2aq_eb_events` e 
WHERE `id` IN (
SELECT `event_id` 
FROM `rf2aq_eb_registrants` r 
GROUP BY `event_id` 
HAVING sum(`number_registrants`) < `event_capacity` 
) 
+0

謝謝你的回答,但MySql發送錯誤:操作數應該包含1列 –

+0

@VadimKozhevnikov請注意,select僅選擇'event_id'而不是總和。 – apokryfos

+0

由於查詢SQL工作,但在PHP中沒有。 –

4

您不必使用子查詢。

SELECT `e`.* FROM `rf2aq_eb_events` as `e` 
LEFT JOIN `rf2aq_eb_registrants` as `r` 
ON `r`.`events_id`=`e`.`ID` 
GROUP BY `r`.`events_id` 
HAVING SUM(`r`.`number_registrants `) < `e`.`event_capacity` 
相關問題