0

I'm running this query but it's very slow. The OR clause on the last left join is what bogs it down, but I can't figure out another way to structure the query in order to obtain the results I'm looking for:

SELECT *,
       DATE_FORMAT(tbl1.pub, '%m/%d/%Y') AS pub_a,
       CONCAT(tbl1.code1, tbl1.code2) AS code_a
FROM (tbl1
      INNER JOIN tbl2 ON tbl1.pkid=tbl2.fkid
      LEFT JOIN tbl3 ON tbl1.pkid=tbl3.fkid)
LEFT JOIN tbl4 ON tbl1.person=tbl4.code OR tbl3.person=tbl4.code
WHERE tbl1.subcat != ''
  AND tbl1.pub < '2014-01-15 13:20:23'
  AND tbl1.exp > '2014-01-15 13:20:23'
ORDER BY tbl1.pub DESC 
LIMIT 0, 50
2
  • 1
    What we really love is when you write it all out on one line like that. Commented Jan 15, 2014 at 21:42
  • I personally love having to figure out the CREATE TABLE schema and SHOW INDEXES FROM. Commented Jan 15, 2014 at 21:44

2 Answers 2

2

Unfortunately, optimizing or in an on clause is not easy. You could split this into two queries, combined with a union:

select *
from ((SELECT *,
              DATE_FORMAT(tbl1.pub, '%m/%d/%Y') AS pub_a,
              CONCAT(tbl1.code1, tbl1.code2) AS code_a
        FROM (tbl1
              INNER JOIN tbl2 ON tbl1.pkid=tbl2.fkid
              LEFT JOIN tbl3 ON tbl1.pkid=tbl3.fkid
              )
              LEFT JOIN tbl4 ON tbl3.person=tbl4.code
        WHERE tbl1.subcat != ''
          AND tbl1.pub < '2014-01-15 13:20:23'
          AND tbl1.exp > '2014-01-15 13:20:23'
        ORDER BY tbl1.pub DESC 
        LIMIT 0, 50
       ) union
       (SELECT *,
              DATE_FORMAT(tbl1.pub, '%m/%d/%Y') AS pub_a,
              CONCAT(tbl1.code1, tbl1.code2) AS code_a
        FROM (tbl1
              INNER JOIN tbl2 ON tbl1.pkid=tbl2.fkid
              LEFT JOIN tbl3 ON tbl1.pkid=tbl3.fkid
              )
              LEFT JOIN tbl4 ON tbl1.person=tbl4.code
        WHERE tbl1.subcat != ''
          AND tbl1.pub < '2014-01-15 13:20:23'
          AND tbl1.exp > '2014-01-15 13:20:23'
        ORDER BY tbl1.pub DESC 
        LIMIT 0, 50
       )
      ) t
order by pub desc
limit 0, 50
Sign up to request clarification or add additional context in comments.

Comments

1

This is a long shot, but try changing

left join tbl4 on tbl1.person = tbl4.code
    or tbl3.person = tbl4.code

to

left join tbl4 on tbl4.code in (tbl1.person, tbl3.person)

1 Comment

Thanks, that sped it up a little.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.