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

时间:2017-02-02 14:01:21

标签: mysql group-concat

我在子查询中遇到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 |
+-------------------+

1 个答案:

答案 0 :(得分:0)

您需要在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子句。要按相反顺序排序,请在ORDER BY子句中将DESC(降序)关键字添加到要排序的列的名称。 ...

再次,如果你没有任何东西可以通过命名"名称"按照正确的顺序组合,那么你运气不好。因为订单无法保证!