Last active
December 14, 2018 18:09
-
-
Save iprodev/1b814af209c979f7224d2e788aab2d15 to your computer and use it in GitHub Desktop.
SQL : Faster MySQL Counting on JOINS
This file contains 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
SELECT | |
user_accounts.id, | |
user_accounts.company_name, | |
IFNULL(suppliers.count, 0) AS suppliers, | |
IFNULL(customers.count, 0) AS customers, | |
IFNULL(inventory_transactions.count, 0) AS transactions | |
FROM user_accounts | |
LEFT JOIN (SELECT | |
user_account_id, | |
COUNT(*) AS count | |
FROM inventory_transactions | |
GROUP BY user_account_id) inventory_transactions | |
ON inventory_transactions.user_account_id = user_accounts.id | |
LEFT JOIN (SELECT | |
user_account_id, | |
COUNT(*) AS count | |
FROM customers | |
GROUP BY user_account_id) customers | |
ON customers.user_account_id = user_accounts.id | |
LEFT JOIN (SELECT | |
user_account_id, | |
COUNT(*) AS count | |
FROM suppliers | |
GROUP BY user_account_id) suppliers | |
ON suppliers.user_account_id = user_accounts.id | |
GROUP BY user_accounts.id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment