Last active
February 24, 2017 08:59
-
-
Save lenguyenthedat/26cf3c466c54c1608cad9cd0b1c12fe4 to your computer and use it in GitHub Desktop.
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
-- Bad: multiple type of joins unecessarily used, start from `orders` as base table is not ideal | |
SELECT | |
DATE(orders.created_at) AS date, | |
users.email | |
FROM orders | |
LEFT JOIN users | |
ON users.id = orders.user_id | |
JOIN order_items | |
ON order_items.order_id = orders.id | |
GROUP BY 1, 2 | |
HAVING COUNT(order_items.id) > 10 | |
-- Good: | |
SELECT | |
DATE(orders.created_at) AS date, | |
users.email | |
FROM order_items | |
LEFT JOIN orders | |
ON orders.id = order_items.order_id | |
LEFT JOIN users | |
ON users.id = orders.user_id | |
GROUP BY 1, 2 | |
HAVING COUNT(order_items.id) > 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment