MySQL条件分组依据

MySQL条件分组依据,mysql,Mysql,我的数据库看起来(有点)像这样: 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 transla

我的数据库看起来(有点)像这样:

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
翻译
-表中的
参考字段
提供了翻译文本将位于
posts
-表的哪个字段的信息

我希望有一个SELECT,结果是一行,它将相应的文本串联在一起,即

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以便给出预期的结果


任何帮助或提示都将不胜感激!谢谢大家!

我建议如下:

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 Fiddle演示:


一点解释:当您多次使用相同的引用id并加入这两个表时,您将得到比预期更多的行。因此,有必要进行过滤。这就是我使用reference_字段并加入2x time的原因,我建议如下:

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 Fiddle演示:


一点解释:当您多次使用相同的引用id并加入这两个表时,您将得到比预期更多的行。因此,有必要进行过滤。这就是我使用reference_字段并加入2x time

@GordonLinoff的原因:我需要的是概念性的想法,而不是正确的语法。我必须插入CONCAT()-函数-这没有什么坏处。@GordonLinoff我修正了答案,并添加了一个工作SQL Fiddledemo@GordonLinoff:我需要的是概念性的想法,而不是正确的语法。我必须插入CONCAT()-函数-这没有什么坏处。@GordonLinoff我修正了答案,并添加了一个SQL Fiddle演示