I’m far from being a mysql guru, so need to know if there’s a way to make this query faster,shorter and more compact.
(SELECT DISTINCT(cfrm.nid), f.filename, n.title, n.created
FROM content_field_raamatu_marksonad cfrm
LEFT JOIN node n ON (n.nid = cfrm.nid)
LEFT JOIN content_field_kaanepilt cfk ON (cfk.nid = n.nid)
LEFT JOIN files f ON (f.fid = cfk.field_kaanepilt_fid)
WHERE n.type = 'raamat'
AND n.status = 1
AND cfrm.field_raamatu_marksonad_value IN (102, 3348))
UNION
(SELECT DISTINCT(cfrt.nid), f.filename, n.title, n.created
FROM content_field_raamatu_teema cfrt
LEFT JOIN node n ON (n.nid = cfrt.nid)
LEFT JOIN content_field_kaanepilt cfk ON (cfk.nid = n.nid)
LEFT JOIN files f ON (f.fid = cfk.field_kaanepilt_fid)
WHERE n.type = 'raamat'
AND n.status = 1
AND cfrt.field_raamatu_teema_value = 1342)
ORDER BY `created` DESC
About the only way to rewrite it is to do the UNION before you do the LEFT JOINs:
This might save dual scans of the outer joined tables. On the other hand, the optimizer might optimize it like that anyway – though I suspect it probably would not. Replacing the LEFT JOIN operations with JOIN would improve performance – if it does not affect the accuracy of the result. That depends on whether you expect there to be a file name for every row or not – at least in part.