优化mysql选择(性能不佳)

时间:2013-11-15 15:44:09

标签: mysql sql performance select

我有3张桌子:

t1约500.000rows t2 1.600rows t3 50.000rows

我的SQL查询需要(大约)15秒才能在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

索引是:

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

categories (t3):
 id_cat = PRIMARY

posts:
 post_subject = INDEX

目标是根据DATE_OF_RECORD&&amp ;;获得10个订单。 POST_TIME。记录和帖子表未连接,它们代表不同的数据。我试图从我的数据中获取某种“日志”...(t1&& t3),(帖子)....因为它及时...

你能帮我解决一下优化吗?

1 个答案:

答案 0 :(得分:2)

您也可以尝试将LIMIT 10添加到UNION的第一部分。如果你真的只想要10,你会LIMIT 10得到最终结果: 要获得两个组中最新的10个,您应该只将ORDER BYLIMIT放在外面,但如果您可以使用它,则可能会更快:

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

此外,请确保在posts.post_time和records.date_of_record上有索引,以使其执行更快。