从表A模糊查询出结果,能够再B表按条件查询出的结构中找到的数据
下面是sql语句:
select t1.showCode, t1.Name, t1.Sex, t.AppointmentDate from (select *from A where AppointmentDate >= date_sub(current_date(), interval '10' day) and isFinish = 0 ) t
inner join (select *from B where (Name = '%1111%' or showCode like '%1111%') and HospitalID = '20220302160409') t1 on t.PatientID = t1.PatientID order by t.AppointmentDate desc;
这样在结尾加上 order by t.AppointmentDate desc排序语句就变得非常慢,比不加排序语句相差几十倍,请问要如何优化啊?
补充下explain结果如图:
表的数据量有多大 排序字段加个索引试试
把排序放在子查询t里面进行,然后子查询t的字段也可以按需返回,再不然还可以针对排序列建索引
放到子查询排序不起作用,另外排序AppointmentDate 字段也加了索引的,还是不行
确定是加了排序变慢了?而不是sql关联就很慢,只是返回了前面10条,所以很快 不加order by limit 30000 试试呢,
这样试试
select B.showCode, B.Name, B.Sex, A.AppointmentDate
from A ,B
WHERE A.PatientID = B.PatientID
and A.AppointmentDate>=date_sub(current_date(), interval '10' day)
and A.isFinish = 0
and (B.Name like '%1111%' or B.showCode like '%1111%')
and B.HospitalID = '20220302160409'
ORDER BY 4