2

I have 3 tables:

t1 approx 500.000rows t2 1.600rows t3 50.000rows

My SQL query takes (around) 15sec to display results in phpmyadmin.

    SELECT * 
    FROM (
      SELECT NULL AS post_subject, t1.id_rec, t1.name, t1.id_cat, t1.date_of_record
      FROM records AS t1
       INNER JOIN categories AS t3 ON t1.id_cat = t3.id_cat AND t3.private =0
     UNION 
      SELECT post_subject, NULL , NULL , NULL , post_time
      FROM posts
     ORDER BY date_of_record DESC 
     LIMIT 10
    ) a

And indexes are:

records (t1):
 id_rec = PRIMARY
 name = INDEX
 id_cat = INDEX

categories (t3):
 id_cat = PRIMARY

posts:
 post_subject = INDEX

The goal is to get 10rows which are ordered based on DATE_OF_RECORD && POST_TIME. Table of records and posts are not connected and they represent different data. I am trying to get some kind of "log" from my data... (t1&&t3),(posts).... as it goes in time...

Could you help me please with optimization?

2
  • 1
    For future reference, when you've accepted an answer the question will be styled differently wherever it appears on the site; there's no need to edit "solved" into the title. :) Commented Nov 15, 2013 at 16:14
  • ok, I am new here, thank you :) Commented Nov 15, 2013 at 16:27

1 Answer 1

2

You could try adding LIMIT 10 to the first part of the UNION too. And if you really only want 10, you would LIMIT 10 to the final result: To get the 10 latest of both groups you should only put the ORDER BY and LIMIT outside, but if you can live with that, it may be faster:

SELECT *
FROM ((
  SELECT NULL AS post_subject, t1.id_rec, t1.NAME, t1.id_cat, t1.date_of_record
  FROM records AS t1
  INNER JOIN categories AS t3
    ON t1.id_cat = t3.id_cat
      AND t3.private = 0
  ORDER BY date_of_record DESC LIMIT 10)      
  UNION      
  (SELECT post_subject, NULL, NULL, NULL, post_time
  FROM posts
  ORDER BY post_time DESC LIMIT 10)
  ) a
ORDER BY date_of_record DESC LIMIT 10

Additionally, make sure you have indexes on posts.post_time and records.date_of_record to make this execute faster.

Sign up to request clarification or add additional context in comments.

6 Comments

The 2-nd ORDER BY has to be post_time DESC. And he will need to have indexes on records.date_of_record and posts.post_time.
This gives me: #1221 - Incorrect usage of UNION and ORDER BY :(
@FredericoRossini throw some ()-s at it :)
(MySQL: 5.5.31, phpMyAdmin - 2.9.0.2)
@FredericoRossini. Try now with extra ()'s .
|

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.