简体   繁体   中英

Concatenating values in mysql where multiple rows in one table relate to one row in another table

I have two mysql tables, one listing article names, the other listing the authors associated with each article, as follows:

   article_id     title
 =======================
        1         art1
        2         art2
        3         blob


  article_id      name      surname
 =====================================
       1           jack       smith
       1           jill       jones
       1           rob        edgar
       2           billy      bryce
       3           dick       bonsor
       3           jeff       kucick

I am trying to create a query that will return the following:

 article_id     title                 author
 =========================================================
      1          art1     jack smith, jill jones, rob edgar 
      2          art2                billy bryce
      3          blob          dick bonsor, jeff kucick

I have been looking at group_concat and concat_ws, but I have been unsuccessful in my attempts to return the above result. If any of you have any thoughts on this, I would be most grateful!

Many thanks.

select
  a.article_id,
  a.title,
  group_concat(concat(p.name, ' ', p.surname)) as author
from
  article a
  inner join author p on p.article_id = a.article_id
group by
  a.article_id, 
  a.title

or, if you want to use concat_ws:

select
  a.article_id,
  a.title,
  group_concat(concat_ws(' ', p.name, p.surname)) as author
from
  article a
  inner join author p on p.article_id = a.article_id
group by
  a.article_id, 
  a.title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM