简体   繁体   中英

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

SQL query:

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:

  • id
  • col_A
  • active
  • t2_ID

Table t2 indexes:

  • id
  • col_A
  • 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.

I am having a problem identifying how to optimize this query.

Edited as requested, adding 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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