在带有CASE语句的Sqlite查询中被DRY

时间:2018-11-07 12:23:30

标签: sqlite case dry

在以下(有效)查询中:

SELECT q.id, q.section_id, q.type, q.required, q.condition,
CASE WHEN (t1.text_1 IS NULL) THEN
    CASE WHEN ((SELECT t2.text_1 FROM translations t2 WHERE t2.item_id = q.id AND t2.item_model = 'questions' AND t2.language = 'en' LIMIT 1) IS NULL) THEN 
        (SELECT t3.text_1 FROM translations t3 WHERE t3.item_id = q.id AND t3.item_model = 'questions' LIMIT 1)
    ELSE
        (SELECT t2.text_1 FROM translations t2 WHERE t2.item_id = q.id AND t2.item_model = 'questions' AND t2.language = 'en' LIMIT 1)
    END
ELSE
    t1.text_1
END
AS translation
FROM questions q
LEFT JOIN translations t1 ON t1.item_id = q.id
    AND t1.item_model = 'questions'
    AND t1.language = 'fr'
ORDER BY q.position

您可以看到部分(SELECT t2.text_1 FROM translations t2 WHERE t2.item_id = q.id AND t2.item_model = 'questions' AND t2.language = 'en' LIMIT 1)被重复了两次(第一个检查它是否为空,第二个获取值)。

重复的相同查询是否会导致性能问题(我想是)?
有没有更好的方法来重写此查询,将其设为DRY?

1 个答案:

答案 0 :(得分:1)

您可以将内部CASE语句替换为coalesce()函数:

coalesce(SELECT t2.text_1 FROM translations t2 WHERE t2.item_id = q.id AND t2.item_model = 'questions' AND t2.language = 'en' LIMIT 1,
SELECT t3.text_1 FROM translations t3 WHERE t3.item_id = q.id AND t3.item_model = 'questions' LIMIT 1)

来自documenation

  

coalesce(X,Y,...)

     

coalesce()函数返回其第一个非NULL参数的副本,   如果所有参数均为NULL,则返回NULL。 Coalesce()必须至少具有2   争论。

类似的是ifnull()函数。