Skip to content

Instantly share code, notes, and snippets.

@lenguyenthedat
Last active February 24, 2017 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lenguyenthedat/26cf3c466c54c1608cad9cd0b1c12fe4 to your computer and use it in GitHub Desktop.
Save lenguyenthedat/26cf3c466c54c1608cad9cd0b1c12fe4 to your computer and use it in GitHub Desktop.
-- 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