individual SQL select queries vs single big SQLselect query: what is better & why? [closed]
-
16-06-2021 - |
Question
I have these three separate queries, here is the pseudo version of them:
SELECT packageid from tblhosting where userid=1234 AND id=4351
SELECT id FROM tblcustomfields WHERE relid =tblhosting.packageid AND fieldname ='foo'
SELECT value FROM `tblcustomfieldsvalues` WHERE `fieldid` =tblcustomfields.id AND relid=tblhosting.id
currently, these are separate queries & they appear as SUBqueries of each. does it make sense to combine them into single query? if yes, then why & how should one combine this?
Solution
Sorry to be a bit dense, but your question doesn't appear to use subqueries.
If the real code is using subqueries, along the lines of
SELECT value
FROM `tblcustomfieldsvalues`
WHERE `fieldid` =
(SELECT id
FROM tblcustomfields
WHERE relid =(
SELECT packageid
from tblhosting
where userid=1234
AND id=4351)
AND fieldname ='foo')
AND relid=tblhosting.id
then you only have to compare it with @Chopin's version to see that a join is far nicer from a readability point of view.
Joins are also the idiomatic way to do this - most SQL developers looking at the subquery-based approach would scratch their head; this makes it less maintainable and extensible.
In terms of performance, I'm guessing the query optimizer will recognize they're equivalent; there may not be any improvement from the "nicer" version.
OTHER TIPS
The query could be something like this:
SELECT value FROM tblcustomfieldsvalues
INNER JOIN tblcustomfields ON tblcustomfields.id = tblcustomfieldsvalues.fieldid
INNER JOIN tblhosting ON tblhosting.packageid = tblcustomfields.relid
WHERE tblcustomfields.fieldname = 'foo' AND tblhosting.userid = 1234 AND tblhosting.id = 4351
Here you're joining tblcustomfieldsvalues
with tblcustomfields
, and the last with tblhosting
. Look at the ON
conditions to be sure they're correctly joined.
Finally, apply the WHERE
clause on the attributes you want to constraint.
Hope this helps!