Skip to content

Instantly share code, notes, and snippets.

@mohnish
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save mohnish/a4259cdf60733224211e to your computer and use it in GitHub Desktop.

Select an option

Save mohnish/a4259cdf60733224211e to your computer and use it in GitHub Desktop.
SELECT b.name as bill, c.name as category, p.amount as amount, ps.name as card, ps.type as card_type
FROM payments as p, bills as b, categories as c, payment_sources as ps
WHERE b.user_id = 1 AND p.bill_id = b.id AND ps.id = p.payment_source_id AND c.id = b.category_id
;
SELECT b.name as bill, c.name as category, p.amount as amount, ps.name as card, ps.type as card_type
FROM bills as b
INNER JOIN payments as p
ON p.bill_id = b.id
INNER JOIN categories as c
ON c.id = b.category_id
INNER JOIN payment_sources as ps
ON ps.id = p.payment_source_id
WHERE b.user_id = 1
;
@mohnish

mohnish commented Apr 15, 2015

Copy link
Copy Markdown
Author

accuracy of results and performance

@korada

korada commented Apr 15, 2015

Copy link
Copy Markdown

both are accurate. But, joins are faster than sub query and left join is faster than inner join

@mohnish

mohnish commented Apr 15, 2015

Copy link
Copy Markdown
Author

i agree joins are faster. the first query gives you redundant results and is a slower query.

@appikonda

Copy link
Copy Markdown

Query 1: "ps.user_id = b.user_id"
Query 2: "ON ps.id = p.payment_source_id"
both are different conditions baa

@mohnish

mohnish commented Apr 15, 2015

Copy link
Copy Markdown
Author

you're right. let me update that first one.

@mohnish

mohnish commented Apr 15, 2015

Copy link
Copy Markdown
Author

there you go

@appikonda

Copy link
Copy Markdown

Now, both are accurate.

@mohnish

mohnish commented Apr 15, 2015

Copy link
Copy Markdown
Author

you're right. and speed wise, both are similar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment