简体   繁体   English

Mysql 行号非常慢

[英]Mysql row number with order by very slow

I have this query我有这个查询

select courses.id, y.qs_world, courses.name_en as name, 
courses.description_en as description,
source_link, courses.slug, fee, duration, courses.university_id, college_id,
study_level_id, application_fee, courses.currency_id 
from courses
left join university_ranks as y on courses.university_id = y.university_id
and y.year = '2021' 
left join universities on courses.university_id = universities.id
left join countries on countries.id = universities.country_id where courses.status = 1

order by ROW_NUMBER() OVER (PARTITION BY countries.id ORDER BY courses.id)

This query is taking too long to execute, but it is working well if I remove the last row.此查询执行时间过长,但如果我删除最后一行,它运行良好。

I used indexing but nothing different.我使用了索引,但没有什么不同。

The EXPLAIN notes are to Using temporary,Using filesort but I want to improve the query without using temporary or filesort EXPLAIN说明是Using temporary,Using filesort但我想改进查询而不使用temporaryfilesort

How can I achieve this?我怎样才能做到这一点?

UPDATE : I tried this query but same speed更新:我试过这个查询,但速度相同

SELECT * FROM (    
     SELECT
      `courses`.`id`,`courses`.`status`,  `y`.`qs_world`, `courses`.`name_en` as `name`, `courses`.`description_en` as `description`,
 `source_link`, `courses`.`slug`, `fee`, `duration`, `courses`.`university_id`, `college_id`,
 `study_level_id`, `application_fee`, `courses`.`currency_id`, `countries`.`id` as country_id
    FROM
      courses
      left join `university_ranks` as `y` on `courses`.`university_id` = `y`.`university_id`
 and `y`.`year` = '2021'
 left join `universities` on `courses`.`university_id` = `universities`.`id`
 left join `countries` on `countries`.`id` = `universities`.`country_id`
 
) UserCourse  where status = 1
order by ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY id) 
  • countries . countries id as country_id --> universities . id为 country_id --> universities country_id

  • then remove然后删除

     left join `countries` ON `countries`.`id` = `universities`.`country_id`
  • Move where status = 1 into the inner query.where status = 1移动到内部查询中。

  • It seems like这好像是

     order by ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY id)

    could be replaced by可以替换为

     ORDER BY country_id, id
  • Get rid of the outer query摆脱外部查询

  • Don't say LEFT unless the 'right' table might have a missing row.除非“右”表可能缺少行,否则不要说LEFT (It confuses the reader as to your intent.) (它使读者对您的意图感到困惑。)

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

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