条件的查询速度

时间:2019-10-11 14:06:16

标签: mysql sql

给出的结果和结果均相同。在SELECT(CASE WHEN)处添加条件是否比在WHERE处查询更快?

/*On SELECT*/    
        SELECT
            COUNT(*) as totaal,
            SUM(general_score_filter.dash) as totaal_score
        FROM (
        SELECT 
            operatie.id as operatie_id,
            AVG(CASE WHEN patient.inactief = 0 AND vraag.eigenschap_id = _eigenschap_id THEN antwoord.score ELSE 0 END) AS dash
        FROM
        operatie
            LEFT JOIN antwoord ON operatie.id = antwoord.operatie_id AND antwoord.deleted = 0
            LEFT JOIN vraag ON vraag.id = antwoord.vraag_id AND vraag.deleted = 0
            LEFT JOIN patient ON operatie.patient_id = patient.id AND patient.inactief = 0
        GROUP BY operatie.id) AS general_score_filter;

/*On WHERE*/
        SELECT
            COUNT(*) as totaal,
            SUM(general_score_filter.dash) as totaal_score
        FROM (
        SELECT 
            operatie.id as operatie_id,
            AVG(CASE WHEN vraag.eigenschap_id = _eigenschap_id THEN antwoord.score ELSE 0 END) AS dash
        FROM
        operatie
            LEFT JOIN antwoord ON operatie.id = antwoord.operatie_id AND antwoord.deleted = 0
            LEFT JOIN vraag ON vraag.id = antwoord.vraag_id AND vraag.deleted = 0
            LEFT JOIN patient ON operatie.patient_id = patient.id AND patient.inactief = 0
        WHERE
            patient.inactief = 0
        GROUP BY operatie.id) AS general_score_filter;

1 个答案:

答案 0 :(得分:1)

这完全取决于您的数据量。您可能不会注意到50k至100k的小型数据集,但是如果您有数百万行,那么您会发现。

但是总的来说,是的,在WHERE子句中使用不活动状态的索引会更快。根据下面的示例数据,您将跳过所有“ inactief = 1”记录,但是,对于您的答案,它会更准确。您是否要所有人,还是只希望那些无动于衷的人?0。阅读下文

“示例”表中包含以下记录的示例

id    inactief      score (via the join to antwoord)
1     0             10
1     0             20
1     1             30
1     0             40
1     1             50
1     1             60
1     0             70
2     1             15
2     1             25
3     0             38

假设您的第一个查询,您的最终计数将有所有3位患者(1、2和3)。您的第二个计数where“ inactief = 0”子句将仅返回2位患者(1和3),因为患者2的所有记录均具有inactief =1。

我也同意不赞成投票。如果您在投票方面有问题,请至少告诉我什么地方出了问题,这样我以后就可以对自己的职位做得更好。有些人只是喜欢无礼,但是您能做什么。