Results 1 to 2 of 2

Thread: CONCAT statement

  1. #1
    Join Date
    Mar 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default CONCAT statement

    I got stuck with this statement.

    I have two tables:

    Author: author_id, author_name
    Wrote: book_id, author id

    I want to get book_id with all its authors in one field, concatenating all the authors' names.

    For instance, let's suppose we have

    Wrote:
    book_id author_id
    10 50
    10 51
    10 52
    11 53

    Author:
    author_id author_name
    50 John
    51 Mike
    52 Lisa
    53 Rachel

    I want to make a select statement which brings:

    book_id Authors
    10 John, Mike, Lisa
    11 Rachel


    Please HELP!!!

  2. #2
    Join Date
    Jan 2007
    Location
    Davenport, Iowa
    Posts
    2,385
    Thanks
    100
    Thanked 113 Times in 111 Posts

    Default

    Code:
    SELECT wrote.book_id, GROUP_CONCAT(author.author_name) 
    FROM author, wrote 
    WHERE author.author_id=wrote.author_id 
    GROUP BY wrote.book_id
    This generates:
    Code:
    book_id	GROUP_CONCAT(author.author_name)
    
    10	John,Mike,Lisa
    11	Rachel
    This helps to consolidate the values like you were asking instead of the following where each row with a different name is listed one at a time each with its own row.

    Code:
    SELECT wrote.book_id, author.author_name 
    FROM author, wrote 
    WHERE author.author_id=wrote.author_id
    which produces:
    Code:
    book_id	author_name
    
    10	John
    10	Mike
    10	Lisa
    11	Rachel
    I know this is a late response.

    Further reading:

    GROUP BY
    GROUP_CONCAT()
    Last edited by james438; 04-21-2011 at 05:28 AM. Reason: Reformatted for readability
    To choose the lesser of two evils is still to choose evil. My personal site

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •