简体   繁体   中英

How to alter the SQL query to make it execute faster for larger data sets?

I can't understand what's wrong with my SQL query.

I have tried indexing the required columns but it was not good.

Here is a part of my query, (which seems to be an issue)

select 
      t1.column1, 
      t2.column2, 
      t1.column3, 
      t1.column4, 
      t1.column5 
   from 
      table_1 as t1 
         left join 
         (select 
               column1,
               column2,
               column3 
            from 
               table_2 
            where 
               column3 = 1) as t2 
           on t1.column1 = t2.column1 
   order by 
      t1.column1

I tried the following as well

select 
      t1.column1, 
      t2.column2, 
      t1.column3, 
      t1.column4, 
      t1.column5 
   from 
      table_1 as t1 
         left join table_2 as t2 
            on  t1.column1 = t2.column1 
            and t2.column3 = 1 
   order by 
      t1.column1

The above code executes slowly when data in the tables are more than 3k. It usually takes milliseconds to retrieve the information but when data increases to 2k-10k it takes 2 seconds or 3 seconds.

I was wondering if there is any solution to increase the performance of the above SQL query.

The issue I found arises from order by statement.

No ,mysql performence depends on The length of result data ,not on query. Thanks

Without context of the true tables, nobody will have any idea as to the possibility of multiple rows for the secondary table. That said, you WILL be getting every row from table1, but if there are multiple rows in table2, you will have multiple rows returned (which is ok).

The only real way to hope to optimize the query is by having appropriate indexes.

Your Table1 should have an index on (column1) as that is the basis of the ORDER BY clause... You would also add other columns if you were applying a WHERE clause to your table1 to optimize the filtering of such records.

For Table2, you would be better to have a covering index on the 3 fields and in order of ( column3, column1, column2). Column3 due to the WHERE clause to optimize that. Column 1 as that is the basis of the LEFT-JOIN to table1. Finally column2 as that is the only column you are pulling from the subquery if such record IS found.

In your subquery, you don't even need to return the column3 as you pre-qualified it as a specific value and it is not used in the final result set.

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