【原创】MySQL新旧版本ORDERBY处理方法
MySQL 的order by 涉及到三个参数: A. sort_buffer_size 排序缓存。 B. read_rnd_buffer_size 第二次排序缓存。 C. max_length_for_sort_data 带普通列的最大排序约束。 我来简单说下MySQL的排序规则。 假设查询语句select * from tb1 where 1 order by a ;
MySQL 的order by 涉及到三个参数:
A. sort_buffer_size 排序缓存。
B. read_rnd_buffer_size 第二次排序缓存。
C. max_length_for_sort_data 带普通列的最大排序约束。
我来简单说下MySQL的排序规则。
假设查询语句select * from tb1 where 1 order by a ; 字段a没有建立索引;以上三个参数都足够大。
MySQL内部有两种排序规则:
第一种,是普通的排序。这种排序的特点是节省内存,但是最终会对磁盘有一次随机扫描。 大概主要过程如下:
1. 由于没有WHERE条件,所以直接对磁盘进行全表扫描,把字段a以及每行的物理ID(假设为TID)拿出来。然后把所有拿到的记录全部放到sort_buffer_size中进行排序。
2. 根据排好序的TID,从磁盘随机扫描所需要的所有记录,排好序后再次把所有必须的记录放到read_rnd_buffer_size中。
第二种,是冗余排序。这种排序的特点是不需要二次对磁盘进行随机扫描,但是缺点很明显,太浪费内存空间。
跟第一种不同的是,在第一步里拿到的不仅仅是字段a以及TID,而是把所有请求的记录全部拿到后,放到sort_buffer_size中进行排序。这样可以直接从缓存中返回记录给客户端,不用再次从磁盘上获取一次。
从MySQL 5.7 后,对第二种排序进行了打包压缩处理,避免太浪费内存。比如对于varchar(255)来说,实际存储为varchar(3)。那么相比之前的方式节约了好多内存,避免缓存区域不够时,建立磁盘临时表。
以下为简单的演示
mysql> use t_girl; Database changed
三个参数的具体值:
mysql> select truncate(@@sort_buffer_size/1024/1024,2)||'MB' as 'sort_buffer_size',truncate(@@read_rnd_buffer_size/1024/1024,2)||'MB' as read_rnd_buffer_zie,@@max_length_for_sort_data as max_length_for_sort_data; +------------------+---------------------+--------------------------+ | sort_buffer_size | read_rnd_buffer_zie | max_length_for_sort_data | +------------------+---------------------+--------------------------+ | 2.00MB | 2.00MB | 1024 | +------------------+---------------------+--------------------------+ 1 row in set (0.00 sec)
演示表的相关数据:
mysql> select table_name,table_rows,concat(truncate(data_length/1024/1024,2),'MB') as 'table_size' from information_schema.tables where table_name = 't1' and table_schema = 't_girl'; +------------+------------+------------+ | table_name | table_rows | table_size | +------------+------------+------------+ | t1 | 2092640 | 74.60MB | +------------+------------+------------+ 1 row in set (0.00 sec)
开启优化器跟踪:
mysql> SET OPTIMIZER_TRACE="enabled=on",END_MARKERS_IN_JSON=on; Query OK, 0 rows affected (0.00 sec)
从数据字典里面拿到跟踪结果:
mysql> select * from information_schema.optimizer_trace\G *************************** 1. row *************************** QUERY: select * from t1 where id < 10 order by id TRACE: { "steps": [ { "join_preparation": { "select#": 1, "steps": [ { "expanded_query": "/* select#1 */ select `t1`.`id` AS `id`,`t1`.`log_time` AS `log_time` from `t1` where (`t1`.`id` < 10) order by `t1`.`id`" } ] /* steps */ } /* join_preparation */ }, { "join_optimization": { "select#": 1, "steps": [ { "condition_processing": { "condition": "WHERE", "original_condition": "(`t1`.`id` < 10)", "steps": [ { "transformation": "equality_propagation", "resulting_condition": "(`t1`.`id` < 10)" }, { "transformation": "constant_propagation", "resulting_condition": "(`t1`.`id` < 10)" }, { "transformation": "trivial_condition_removal", "resulting_condition": "(`t1`.`id` < 10)" } ] /* steps */ } /* condition_processing */ }, { "table_dependencies": [ { "table": "`t1`", "row_may_be_null": false, "map_bit": 0, "depends_on_map_bits": [ ] /* depends_on_map_bits */ } ] /* table_dependencies */ }, { "ref_optimizer_key_uses": [ ] /* ref_optimizer_key_uses */ }, { "rows_estimation": [ { "table": "`t1`", "table_scan": { "rows": 2092640, "cost": 4775 } /* table_scan */ } ] /* rows_estimation */ }, { "considered_execution_plans": [ { "plan_prefix": [ ] /* plan_prefix */, "table": "`t1`", "best_access_path": { "considered_access_paths": [ { "access_type": "scan", "rows": 2.09e6, "cost": 423303, "chosen": true, "use_tmp_table": true } ] /* considered_access_paths */ } /* best_access_path */, "cost_for_plan": 423303, "rows_for_plan": 2.09e6, "sort_cost": 2.09e6, "new_cost_for_plan": 2.52e6, "chosen": true } ] /* considered_execution_plans */ }, { "attaching_conditions_to_tables": { "original_condition": "(`t1`.`id` < 10)", "attached_conditions_computation": [ ] /* attached_conditions_computation */, "attached_conditions_summary": [ { "table": "`t1`", "attached": "(`t1`.`id` < 10)" } ] /* attached_conditions_summary */ } /* attaching_conditions_to_tables */ }, { "clause_processing": { "clause": "ORDER BY", "original_clause": "`t1`.`id`", "items": [ { "item": "`t1`.`id`" } ] /* items */, "resulting_clause_is_simple": true, "resulting_clause": "`t1`.`id`" } /* clause_processing */ }, { "refine_plan": [ { "table": "`t1`", "access_type": "table_scan" } ] /* refine_plan */ } ] /* steps */ } /* join_optimization */ }, { "join_execution": { "select#": 1, "steps": [ { "filesort_information": [ { "direction": "asc", "table": "`t1`", "field": "id" } ] /* filesort_information */, "filesort_priority_queue_optimization": { "usable": false, "cause": "not applicable (no LIMIT)" } /* filesort_priority_queue_optimization */, "filesort_execution": [ ] /* filesort_execution */, "filesort_summary": { "rows": 62390, "examined_rows": 2097152, "number_of_tmp_files": 0, "sort_buffer_size": 2097152, "sort_mode": "<sort_key, additional_fields>" } /* filesort_summary */ } ] /* steps */ } /* join_execution */ } ] /* steps */ } MISSING_BYTES_BEYOND_MAX_MEM_SIZE: 0 INSUFFICIENT_PRIVILEGES: 0 1 row in set (0.00 sec) mysql>
其中以上红色部分
其他的两种

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









MySQL 8.4(2024년 최신 LTS 릴리스)에 도입된 주요 변경 사항 중 하나는 "MySQL 기본 비밀번호" 플러그인이 더 이상 기본적으로 활성화되지 않는다는 것입니다. 또한 MySQL 9.0에서는 이 플러그인을 완전히 제거합니다. 이 변경 사항은 PHP 및 기타 앱에 영향을 미칩니다.

PHP가 MySQL에 연결 한 후 페이지가 비어 있고 Die () 함수가 실패한 이유가 있습니다. PHP와 MySQL 데이터베이스 간의 연결을 배울 때는 종종 혼란스러운 것들이 발생합니다 ...

PHP ...

많은 웹 사이트 개발자는 램프 아키텍처에서 Node.js 또는 Python 서비스를 통합하는 문제에 직면 해 있습니다. 기존 램프 (Linux Apache MySQL PHP) 아키텍처 웹 사이트 요구 사항 ...

PC 및 모바일 측면에서 동일한 페이지를 공유하고 캐시 문제를 처리하는 방법은 무엇입니까? Baota 배경, PC 측면을 만드는 방법 및 ...

이 기사에서 PHP 낙관적 잠금 및 거래와 함께 균형을 공제하는 문제에 대한 자세한 설명은 PHP, 낙관적 잠금 및 데이터베이스 트랜잭션을 사용한 균형 공제를 자세히 분석합니다.

Redis 데이터베이스를 효과적으로 모니터링하는 것은 최적의 성능을 유지하고 잠재적인 병목 현상을 식별하며 전반적인 시스템 안정성을 보장하는 데 필수적입니다. Redis 내보내기 서비스는 다음을 사용하여 Redis 데이터베이스를 모니터링하도록 설계된 강력한 유틸리티입니다.

"Debiantrings"는 표준 용어가 아니며 구체적인 의미는 여전히 불분명합니다. 이 기사는 브라우저 호환성에 직접 언급 할 수 없습니다. 그러나 "Debiantrings"가 Debian 시스템에서 실행되는 웹 응용 프로그램을 지칭하는 경우 브라우저 호환성은 응용 프로그램 자체의 기술 아키텍처에 따라 다릅니다. 대부분의 최신 웹 응용 프로그램은 크로스 브라우저 호환성에 전념합니다. 이는 웹 표준에 따라 웹 표준과 잘 호환 가능한 프론트 엔드 기술 (예 : HTML, CSS, JavaScript) 및 백엔드 기술 (PHP, Python, Node.js 등)을 사용하는 데 의존합니다. 응용 프로그램이 여러 브라우저와 호환되도록 개발자는 종종 브라우저 크로스 테스트를 수행하고 응답 성을 사용해야합니다.
