mySQL优化查询以便快速获取

时间:2015-12-17 17:28:40

标签: mysql

我有这样的事情:

SELECT INCOME
FROM PATIENTS
JOIN CASES
ON PATIENT_ID = CASE_PATIENT_ID
WHERE YEAR(DATE_OF_BIRTH) = '1955' AND YEAR(CASE_DATE)>'2000'
GROUP BY INCOME

我的问题是两个表(PATIENTS和CASES)都有数百万行,而year()会禁用我的索引并使我的查询非常慢。

如何优化它以便更快地运行? (我尝试使用嵌套的SELECT以仅提取我想要的日期,但它什么也不返回)。

提前谢谢!

编辑:由于我的问题可能看起来有点模糊,因此PLZ帮助我优化以下代码,因为它在获取时陷入困境。

    select round(avg(INCOME_PER_MONTH),2) as Average_Income,
case
    when WEIGHT/(HEIGHT*HEIGHT)*10000 < 15 then "Very Severly Underweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 15 and 16 then "Severly Underweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 16.1 and 18.5 then "Underweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 18.6 and 25 then "Normal (healthy weight)"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 25.1 and 30 then "Overweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 30.1 and 35 then "Obese Class I"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 35.1 and 40 then "Obese Class II"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 > 40 then "Obese Class III"
end
as BMI,
WEIGHT/(HEIGHT*HEIGHT)
from PATIENTS
join CASES
on PATIENT_ID = PAT_ID and PATIENTS.PATIENT_ID = CASES.PAT_ID
where CASES.DATE_OF_CONT  between '2005-01-01' and '2010-12-31'
and PATIENTS.DATE_OF_BIRTH between '1995-01-01' and '1995-12-31'
group by
case
    when WEIGHT/(HEIGHT*HEIGHT)*10000 < 15 then "Very Severly Underweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 15 and 16 then "Severly Underweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 16.1 and 18.5 then "Underweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 18.6 and 25 then "Normal (healthy weight)"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 25.1 and 30 then "Overweight"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 30.1 and 35 then "Obese Class I"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 between 35.1 and 40 then "Obese Class II"
    when WEIGHT/(HEIGHT*HEIGHT)*10000 > 40 then "Obese Class III"
end

所有列都有索引,每个列都有几百万行。

我的目标是显示特定年份出生的患者的平均收入,并在2005年至2010年期间与我们联系。

我希望它证明自己是一个适当的挑战;)

1 个答案:

答案 0 :(得分:0)

它不漂亮,但这应该有效:

SELECT INCOME
FROM PATIENTS
JOIN CASES
ON PATIENT_ID = CASE_PATIENT_ID
WHERE DATE_OF_BIRTH BETWEEN STR_TO_DATE(CONCAT('1955', '-01-01'), '%Y-%m-%d') AND STR_TO_DATE(CONCAT('1955', '-12-31'), '%Y-%m-%d') AND 
      CASE_DATE > STR_TO_DATE(CONCAT('2000', '-12-31'), '%Y-%m-%d')
GROUP BY INCOME