mercredi 12 août 2015

Optimizing a two-level SQL query

Here's the layout of the relevant parts of my database:

database design

(BTW, I made this diagram with wwwsqldesigner)

Now, I like to query all rows of C which match a particular row of A.

The query I came up with myself works. E.g, to look up rows in C matching A's row 123:

SELECT C.* FROM C
LEFT JOIN B1 ON (B1.id = C.id_B1)
LEFT JOIN B2 ON (B2.id = C.id_B2)
WHERE B1.id_A = 123 OR B2.id_A = 123

However, I believe the above query is rather inefficient as it collects all rows of B1 and B2 in a large set before reducing it down again, right?

I believe I should be able to first make a query for B1 and B2 each, selecting for their id_A values, then joins those results somehow into the matching C rows.

I've looked at sqlite.org's docs for the SELECT command but the possibilities overwhelm me.

How does one figure this out? A bit of explaining the thought process of solving this would be appreciated.

(Also, if you could suggest a better title for this question - I don't really know how to pinpoint this)

Aucun commentaire:

Enregistrer un commentaire