Skip to content

Instantly share code, notes, and snippets.

@iprodev
Last active December 14, 2018 18:09
Show Gist options
  • Save iprodev/1b814af209c979f7224d2e788aab2d15 to your computer and use it in GitHub Desktop.
Save iprodev/1b814af209c979f7224d2e788aab2d15 to your computer and use it in GitHub Desktop.
SQL : Faster MySQL Counting on JOINS
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