2009-10-12 114 views
1

我有一个数据库,有问题和答案,可以翻译成网站使用的所有语言。但是当一个问题还没有被翻译时,我想用英语来表达这个问题。所以一个类似gettext的行为。如何优化这个SQL查询?

这个我现在的SQL查询看起来是这样的:

SELECT * FROM questions_view WHERE `language` = "de" AND `#parent` IS NULL 
UNION 
SELECT * FROM questions_view WHERE `language` = "en" AND `#parent` IS NULL 
    AND id NOT IN (SELECT id 
        FROM questions_view 
        WHERE `language` = "de") 

但我觉得这是不是这样做的最佳方式。有小费吗?

+0

代码的编码习惯避免使用通配符*。如果你使用它,你正在为自己建立陷阱。 – markus 2009-10-12 10:49:31

回答

2

此:

SELECT qi.* 
FROM (
     SELECT DISTINCT id 
     FROM questions_view 
     ) qd 
JOIN questions_view qi 
ON  qi.id = qd.id 
     AND qi.language = 
     COALESCE(
     (
     SELECT language 
     FROM questions_view qn 
     WHERE parent IS NULL 
       AND language = 'de' 
       AND qn.id = qd.id 
     ), 
     (
     SELECT language 
     FROM questions_view qn 
     WHERE parent IS NULL 
       AND language = 'en' 
       AND qn.id = qd.id 
     ) 
     ) 

或本:

SELECT COALESCE(qde.question_text, qen.question_text) 
FROM (
     SELECT DISTINCT id 
     FROM questions_view 
     ) qd 
LEFT JOIN 
     questions_view qde 
ON  qde.id = qd.id 
     AND qde.language = 'de' 
LEFT JOIN 
     questions_view qen 
ON  qen.id = qd.id 
     AND qen.language = 'en' 

如果这些查询更好,哪一个取决于您的数据库系统以及数据库中有多少问题需要翻译。

更多细节请参阅本系列文章在我的博客:

+0

谢谢你在这个系列。 MySQL文章提供了一个很好的解决方案。 – 2009-10-13 08:08:54

1

嗯。我想不出任何其他解决方案。你可能会设置languagenull如果问题还没有翻译,这将让你修改如下:

select * from questions_view where `language` = "de" and `#parent` is null 
union 
select * from questions_view where `language` is null and `#parent` is null 

OTOH它可以帮助先翻译问题添加到一个临时表,然后执行“在德国“-check不存在作为

and not exists (select 1 from temp_translated t where t.id = id) 
1

不知道,如果我是正确的,但不是这还不够

select * from questions_view where language in ('de','en') and #parent is null 
+0

无论翻译是否存在,这都会以德语和英语获得。 – Paddy 2009-10-12 10:41:35

+0

明白了。试图让它现在正确。 – danish 2009-10-12 10:55:17

1

通过删除存在并仅采用第一个可用答案,可能删除1次到DB的旅程,例如

Select Top 1 * 
FROM 
(
    select 1 as myRank, * from questions_view where `language` = "de" and `#parent` is null 
    union 
    select 2 as myRank, * from questions_view where `language` = "en" and `#parent` is null 
) A 
Order By myRank asc 
1

我会去danish's answer,此外,而不是通配查询,仅返回列名的您需要,而不是获取它们。

Select col1, col2, col3, col_etc from questions_view where 
language in ('de','en') and #parent is null