random1 Posted March 8, 2009 Share Posted March 8, 2009 I'm currently developing my reports section of my site and currently have the following as one statement. SELECT COUNT(`product_id`) as `total_active_products`, < ---- This should use the field `product_status_id` == 1 as WHERE COUNT(`product_id`) AS `total_inactive_products`, < ---- This should use the field `product_status_id` == 0 as WHERE COUNT(`product_id`) AS `total_products`, AVG(`product_price`) AS `average_product_price` FROM `product`; How do I do this as one statement but have WHERE clauses? Quote Link to comment https://forums.phpfreaks.com/topic/148470-solved-mysql-syntax-for-multi-select/ Share on other sites More sharing options...
Mchl Posted March 8, 2009 Share Posted March 8, 2009 Using subqueries SELECT (SELECT COUNT(`product_id`) FROM `product` WHERE `product_status_id` == 1) AS `total_active_products`, (SELECT COUNT(`product_id`) FROM `product` WHERE `product_status_id` == 0) AS `total_inactive_products`, ... Be aware though, that too many subqueries and your query will get sloooooow... Do I have to mention that `total_inactive_products` = `total_products` - `total_active_products`? That's one subquery less, and some time saved. Quote Link to comment https://forums.phpfreaks.com/topic/148470-solved-mysql-syntax-for-multi-select/#findComment-779590 Share on other sites More sharing options...
random1 Posted March 9, 2009 Author Share Posted March 9, 2009 Thanks I ended up with: SELECT DISTINCT (SELECT COUNT(`product_id`) FROM `product` WHERE `product_status_id` = 0) AS `total_inactive_products`, (SELECT COUNT(`product_id`) FROM `product` WHERE `product_status_id` = 1) AS `total_active_products`, (SELECT COUNT(`product_id`) FROM `product` WHERE `product_status_id` = 2) AS `total_deleted_products`, (SELECT COUNT(`product_id`) FROM `product`) AS `total_products`, (SELECT MIN(`product_price`) FROM `product`) AS `min_product_price`, (SELECT MAX(`product_price`) FROM `product`) AS `max_product_price`, (SELECT AVG(`product_price`) FROM `product`) AS `average_product_price` FROM `product`; I'll keep an eye on execution time and also add it to an SQL transaction. Quote Link to comment https://forums.phpfreaks.com/topic/148470-solved-mysql-syntax-for-multi-select/#findComment-780074 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.