SELECT * FROM table WHERE `id` in … and where sum() less
I'd like to make PHP $where as part of big query. I need something like: SELECT * FROM rf2aq_eb_events WHERE id IN ( SELECT event_id , SUM(number_registrants) summ FROM rf2aq_eb_registrants WHERE summ < event_capacity ); The rf2aq_eb_events table looks like: ID | event_capacity 1 | 7 2 | 5 3 | 9 The rf2aq_eb_registrants table: ID | events_id | number_registrants 1 | 1 | 6 2 | 2 | 2 3 | 3 | 4 4 | 1 | 1 5 | 2 | 0 6 | 3 | 5 I need select events from the 'rf2aq_eb_events' for events with quantity of registrant < then event_capacity. There is event id = 2 respond the condition. i've tried $where = 'a.id IN ( SELECT event_id FROM #__eb_registrants GROUP BY event_id HAVING sum(number_registrants) < a.event_capacity)'; It's working like SQL, but do not in php in the whole Query. Below i've put php result. 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
You can't use the result of an aggregate (e.g. SUM) in a WHERE you can use it in a HAVING but you need to do a GROUP BY in this case as well: 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` )
You don't have to use subqueries. 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`
Creating new SQLite DBs with PDO
Using Singletons in PHP
Programmatically access & post a form that requires session
Zend_Paginator; is it optimized?
How to create an array from output of var_dump in PHP?
MySQL increment value of attribute - misses sometimes(?)
Best way to encode passwords in PHP
Pagenav. By clicking next get next lets say “20” records (php/mysql)
Can I autoload function files without classes in PHP?
EDI X.12 PHP Mapping - resources needed
Localize current time in PHP
Translating php app with gettext
In RegEx, how do you find a line that contains no more than 3 unique characters?
Generating Luhn Checksums
Simple Php Echo
tcpdf - start with existing PDF document