JOIN queries vs multiple queries

Thomas Bonini picture Thomas Bonini · Jul 1, 2009 · Viewed 111.4k times · Source

Are JOIN queries faster than several queries? (You run your main query, and then you run many other SELECTs based on the results from your main query)

I'm asking because JOINing them would complicate A LOT the design of my application

If they are faster, can anyone approximate very roughly by how much? If it's 1.5x I don't care, but if it's 10x I guess I do.

Answer

Frank Forte picture Frank Forte · May 3, 2011

For inner joins, a single query makes sense, since you only get matching rows. For left joins, multiple queries is much better... look at the following benchmark I did:

  1. Single query with 5 Joins

    query: 8.074508 seconds

    result size: 2268000

  2. 5 queries in a row

    combined query time: 0.00262 seconds

    result size: 165 (6 + 50 + 7 + 12 + 90)

.

Note that we get the same results in both cases (6 x 50 x 7 x 12 x 90 = 2268000)

left joins use exponentially more memory with redundant data.

The memory limit might not be as bad if you only do a join of two tables, but generally three or more and it becomes worth different queries.

As a side note, my MySQL server is right beside my application server... so connection time is negligible. If your connection time is in the seconds, then maybe there is a benefit

Frank