2011-06-06 38 views
0

如何选择即10篇文章而不必运行1次查询来获取每篇文章翻译(共11个查询)?我有3张桌子;文化,文章和翻译:选择多个翻译后的文章(记录)

Cultures 
id code language 
-- ---- --------- 
1 en English 
2 no Norwegian 

Articles 
id title content  
-- ----- ------------- 
1 Home Hello, world! 
2 About This is me... 
... 

Translations 
id culture object FK field value 
-- ------- ------ -- ------- --------------- 
1 1  Page 1 title Home 
2 1  Page 1 content Hello, world! 
3 2  Page 1 title Hjem 
4 2  Page 1 content Hei, verden! 
5 1  Page 2 title About 
6 1  Page 2 content This is me... 
7 2  Page 2 title Om 
8 2  Page 2 content Dette er meg... 
... 

任何帮助将不胜感激!

编辑:说我想取所有的文章,翻译成挪威文。这是我的不完整的查询(它尚未连接到FK A.ID):

SELECT 
    a.id, 
    (SELECT tr.value FROM translations tr WHERE tr.object='Page' 
AND field='title' AND tr.culture=2) as title, 
    (SELECT tr.value FROM translations tr WHERE tr.object='Page' 
AND tr.field='content' AND tr.culture=2) as content 
FROM 
    articles a 

编辑2:同样的问题,因为这: Best mysql query for selecting multiple rows that EACH need multiple associative rows from another table

+0

这是功课? – Konerak 2011-06-06 07:19:04

+0

如果您只能抓取文章,您为什么要抓取翻译? – piotrm 2011-06-06 07:21:00

+0

@Konerak不,我迷路了,在一个客户项目上工作,没有超级经验,寻求帮助。 – asdf 2011-06-06 07:23:20

回答

1

好,translations.FK似乎被链接到文章ID 。所以你选择所有文章,并为每篇文章选择所有翻译。

使用此查询,您的应用程序代码将不得不解释“标题”/“内容”的东西。

SELECT c.language, a.title, t.field, t.value 
FROM articles a 
JOIN translations t ON a.ID = t.FK 
JOIN cultures c on t.culture = c.id 

有了这个查询,你会得到一个 '标题' 和 '内容' 一栏

SELECT a.title, t1.value as title, t2.value as content 
FROM articles a 
JOIN translations t1 ON a.ID = t1.FK and t1.field = 'title' 
JOIN translations t2 ON a.ID = t2.FK and t2.field = 'content' 
+0

这将导致X条次数翻译字段的数量。在这种情况下,10x2 = 20。我知道我可以遍历结果并获取所有已翻译的数据,但是,我希望在查询中这样做。那可能吗? – asdf 2011-06-06 07:31:38

+0

那么你需要哪种格式的'翻译数据'?如果你有10篇文章和5种语言,你总会得到50个结果翻译......这没什么不好的。 – Konerak 2011-06-06 07:32:56

+0

对不起,如果我以前不清楚,但我很好奇,是否有一个更紧凑的方法;针对1种特定语言,可以使用每行中已包含“翻译”的值获取指定数量的文章。 – asdf 2011-06-06 07:47:07