我想将PHP $where
作为大查询的一部分。我需要这样的东西:
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&#39;中选择事件。对于具有注册人数量的事件&lt;然后是event_capacity。有事件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
答案 0 :(得分: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`
答案 1 :(得分:0)
您无法在SUM
中使用聚合的结果(例如WHERE
),您可以在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`
)