我的数据库看起来(有点像):
Table 'posts':
ID title text
62 Trees in Europe You can find fine trees in european woods.
63 Animals in Europe The european fauna is mostly harmless.
Table 'translations':
ID reference_id reference_field translation
36 62 title Bäume in Europa
37 62 text Da sind viele Bäume in Europas Wäldern .
44 63 text Die meisten europäischen Tiere sind harmlos.
47 63 title Tiere in Europa
reference_field
- 表格中的translations
提供了翻译文本所代表的posts
- 表格字段的信息。
我想有一行SELECT作为结果,给我一个相应的textes的连接,即
ID title text
62 Trees in Europe // Bäume in Europa You can find fine trees in european woods. // Du kannst in Europas Wäldern viele Bäume finden.
63 Animals in Europe // Tiere in Europa The european fauna is mostly harmless. // Die meisten europäischen Tiere sind harmlos.
我尝试了很多,但无法得到它。我遇到的问题是translation
列的引用在每一行中都会发生变化。我得到的最接近的是一个列正确连接:
SELECT a.id,
IF (t.reference_field LIKE "title", CONCAT(left(a.title,20), ' // ', LEFT(t.value, 20)), LEFT(a.title, 20)) AS title,
IF (t.reference_field LIKE "text", CONCAT(left(a.text,20), ' // ', LEFT(t.value, 20)), LEFT(a.text, 20)) AS summary,
t.reference_field
FROM posts AS a
JOIN translations AS t on a.id = t.reference_id
WHERE a.id=62
AND t.reference_field IN ('introtext', 'title')
GROUP BY a.id;
如何修改SQL以便给出预期结果?
任何帮助或提示都表示赞赏!谢谢!
答案 0 :(得分:0)
我建议如下:
SELECT p.ID
,concat(p.title, ' // ', t_title.translation) AS title
,concat(p.text, ' // ', t_text.translation) AS text
FROM posts AS p
LEFT JOIN translations AS t_title ON p.id = t_title.reference_id
AND t_title.reference_field = 'title'
LEFT JOIN translations AS t_text ON p.id = t_text.reference_id
AND t_text.reference_field = 'text'
SQL小提琴演示:http://sqlfiddle.com/#!9/5ad47d/4/0
一个小解释:当你多次使用相同的reference_id并且你正在加入这两个表时,你会得到更多的行然后你期望。所以有必要过滤。这就是我使用reference_field并加入2x时间的原因