생년월일로 시작하여 연도별로 그룹화해야합니다. 이것은 내가 지금까지 해왔 던 것이다. 500000 개의 레코드로 저장 프로 시저를 실행 한 다음 내가 작성한 쿼리를 실행하면 약 25 초가 걸리는 것을 알 수 있습니다. 어떻게 개선 할 수 있습니까? mysql - 연도 범위별 그룹
create table people(
id int not null auto_increment primary key,
`dob` date
);
delimiter //
drop procedure if exists date_random //
create procedure date_random(in low date,in upp date,in number int)
begin
declare i int default 0;
while i < number do
begin
insert into people (`dob`) values (low + interval rand()* datediff(upp,low) day );
set i = i + 1;
end;
end while;
end //
delimiter ;
call date_random('1910-01-01',curdate(),500000);
delimiter //
create function `age`(dob date) returns int(11)
no sql
begin
return (year(curdate())-year(dob))-(right(curdate(),5)< right(dob,5));
end //
delimiter ;
explain select sql_no_cache
concat_ws('-',min(age(dob)),max(age(dob))) as years,
count(*) as total
from people
group by if(age(dob)=0,1,ceil(age(dob)/5))
이
는의 출력이 더 효율적이 될 수+----+-------------+--------+-------+---------------+------+---------+------+--------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+-------+---------------+------+---------+------+--------+----------------------------------------------+
| 1 | SIMPLE | people | index | NULL | ip | 4 | NULL | 500000 | Using index; Using temporary; Using filesort |
+----+-------------+--------+-------+---------------+------+---------+------+--------+----------------------------------------------+
1 row in set (0.00 sec)
'EXPLAIN'이 선형 스캔을 많이한다고하면 'dob' 열을 인덱싱하는 것으로 시작할 수 있습니다. – Blrfl
답장을 보내 주셔서 감사합니다. 이미 dob 필드에 인덱스를 추가했다는 것을 잊어 버렸습니다. –