如何选择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 :(得分: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'