Created
September 20, 2021 13:29
-
-
Save bingogg14/91e42947550aa4915372067698fa4ca2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Task optimize query for echo count_profiles and amount for each charity | |
### bad practice | |
SELECT | |
`charities`.`id`, | |
`charities`.`name`, | |
COUNT(DISTINCT `charity_profile`.`giving_profile_id`) AS `count_profiles`, | |
SUM(`donate_to_charities`.`amount`) as `amount` | |
FROM | |
`donate_to_charities` | |
RIGHT JOIN `charities` on `charities`.`id` = `donate_to_charities`.`charity_id` | |
LEFT JOIN `charity_profile` on `charities`.`id` = `charity_profile`.`charity_id` | |
GROUP BY | |
`charities`.`name`, | |
`charities`.`id`; | |
### good practice (100x Faster) | |
SELECT `charities`.`id`, | |
`charities`.`name`, | |
( SELECT count(1) count_profiles | |
FROM charity_profile cp WHERE cp.charity_id = charities.id) as count_profiles, | |
( SELECT SUM(dtc.amount) amount | |
FROM donate_to_charities dtc WHERE dtc.charity_id = charities.id) as amount | |
FROM charities; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment