tags:

views:

23

answers:

1

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
A: 

About the only way to rewrite it is to do the UNION before you do the LEFT JOINs:

SELECT DISTINCT x.nid, f.filename, n.title, n.created
  FROM (SELECT DISTINCT cfrm.nid 
          FROM content_field_raamatu_marksonad AS cfrm
         WHERE cfrm.field_raamatu_marksonad_value IN (102, 3348) 
         UNION 
        SELECT DISTINCT cfrt.nid 
          FROM content_field_raamatu_teema AS cfrt
         WHERE cfrt.field_raamatu_teema_value = 1342) AS x
  LEFT JOIN node AS n ON n.nid = x.nid
  LEFT JOIN content_field_kaanepilt AS cfk ON cfk.nid = n.nid
  LEFT JOIN files AS f ON f.fid = cfk.field_kaanepilt_fid
 WHERE n.type = 'raamat' 
   AND n.status = 1
 ORDER BY n.created DESC;

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.

Jonathan Leffler
That did the job, thanks.
Djeux