简体   繁体   English

MySQL - 查询优化 - 按来自不同连接表的多个字段排序

[英]MySQL - query optimization - order by multiple fields from different joined tables

SQL query: SQL查询:

SELECT t1.col_A, t2.col_A, t2.col_B
FROM t1
INNER JOIN t2.ID = t1.t2_ID
WHERE t1.active = 1
ORDER BY t2.col_A ASC, t2.col_B ASC, t1.col_A ASC
LIMIT 0,100

Table t1 indexes:表 t1 索引:

  • id ID
  • col_A可乐
  • active积极的
  • t2_ID t2_ID

Table t2 indexes:表 t2 索引:

  • id ID
  • col_A可乐
  • col_B col_B

In real life, the tables DO NOT SHARE column names.在现实生活中,表不共享列名。

The heavy thing here is the ORDER BY , without it, query takes 0.001 seconds, with it takes 9 to 10 seconds depending on the size of the table.这里最重要的是ORDER BY ,没有它,查询需要 0.001 秒,根据表的大小需要 9 到 10 秒。

I am having a problem identifying how to optimize this query.我在确定如何优化此查询时遇到问题。

Edited as requested, adding EXPLAIN output:按要求编辑,添加EXPLAIN output:

在此处输入图像描述

Try this, i hope it to make a little difference试试这个,我希望它会有所作为

      ANALYZE TABLE t1;
      ANALYZE TABLE t2;
      create index idx_2 on t2 (col_a asc, col_b asc);
      create index idx_1 on t1(col_a asc);

For this query you want two indexes:对于此查询,您需要两个索引:

SELECT t1.col_A, t2.col_A, t2.col_B
FROM t1 INNER JOIN
     t2
     ON t2.ID = t1.t2_ID
WHERE t1.active = 1
ORDER BY t2.col_A ASC, t2.col_B ASC, t1.col_A ASC
LIMIT 0, 100;

The indexes are:索引是:

  • t1(active, t2_id, col_a)
  • t2(id, col_a, col_b)

The second is not necessary if id is a primary key.如果id是主键,则不需要第二个。

Unfortunately, there is no way (short of using a temporary table) to avoid sorting for the order by , because it is combining columns from different tables.不幸的是,没有办法(除了使用临时表)来避免order by排序,因为它正在组合来自不同表的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM