GROUP_CONCAT 在子查询中产生不可预测的结果

GROUP_CONCAT in subquery yields unpredicable results

我在子查询中遇到 group_concat 语句的问题:

select group_concat(name separator " ")title,tmp.p_i
from (
    select name,blog.db_blog_posts_title_words_evanhendler.p_i
    from blog.db_blog_posts_title_words_evanhendler
    join words.words_blog_posts_title
    on blog.db_blog_posts_title_words_evanhendler.s_i=words.words_blog_posts_title.id
    order by blog.db_blog_posts_title_words_evanhendler.id
)tmp
group by tmp.p_i

产生期望的结果:

+-------------------+------+
| title             | p_i  |
+-------------------+------+
| This is the title |    1 |
| This is the title |    2 |
| This is the title |    3 |
| This is the title |    4 |
+-------------------+------+

但是:

select title from blog.db_blog_posts_title_evanhendler left join (
    select group_concat(name separator " ")title,tmp.p_i
    from (
         select name,blog.db_blog_posts_title_words_evanhendler.p_i
         from blog.db_blog_posts_title_words_evanhendler
        join words.words_blog_posts_title
        on blog.db_blog_posts_title_words_evanhendler.s_i=words.words_blog_posts_title.id
        order by blog.db_blog_posts_title_words_evanhendler.id
    )tmp
    group by tmp.p_i
)tmp 
on blog.db_blog_posts_title_evanhendler.id=tmp.p_i;

产量:

+-------------------+
| title             |
+-------------------+
| is the title This |
| This is the title |
| This is the title |
| This is the title |
+-------------------+

您需要 group_concat 中的可选参数 ORDER BY。前几次您很幸运地获得了订单,但是额外的加入导致引擎将其置于不同的顺序。所以....

GROUP_CONCAT(name ORDER BY Some_field_or_Fields_which_will_put_name_in_right_Order_For_you 
SEPARATOR " " )

摘自Docs

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

在MySQL中,您可以获得表达式组合的串联值。要消除重复值,请使用 DISTINCT 子句。要对结果中的值进行排序,请使用 ORDER BY 子句。要以相反的顺序排序,请将 DESC(降序)关键字添加到您在 ORDER BY 子句中作为排序依据的列的名称。 ...

同样,如果您没有任何东西可以按正确的顺序组合 "names",那么您就不走运了。否则无法保证订单!