Jump to content

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/148470-solved-mysql-syntax-for-multi-select/
Share on other sites

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.

 

Thanks :D

 

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.