[英]Mysql row number with order by very slow
我有這個查詢
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)
此查詢執行時間過長,但如果我刪除最后一行,它運行良好。
我使用了索引,但沒有什么不同。
EXPLAIN
說明是Using temporary,Using filesort
但我想改進查詢而不使用temporary
或filesort
我怎樣才能做到這一點?
更新:我試過這個查詢,但速度相同
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
。 id
為 country_id --> universities
。 country_id
然后刪除
left join `countries` ON `countries`.`id` = `universities`.`country_id`
將where status = 1
移動到內部查詢中。
這好像是
order by ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY id)
可以替換為
ORDER BY country_id, id
擺脫外部查詢
除非“右”表可能缺少行,否則不要說LEFT
。 (它使讀者對您的意圖感到困惑。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.