Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging column values in many to many relationship joins

I have two tables, Books and Authors, with many-to-many relationship between them through a third table called book_authors, i am trying to list all the books with the authors for each book using an inner join in order to display them in a DataList Control, but the join is causing several duplicate rows, because each book may have many authors, so there will be a row for each author.
Example:

book_title           author  
b1                    a1  
b1                    a2  

What is the best way to fix this so it becomes:

book_title                author  
b1                        a1, a2  
like image 200
Ibrahim Najjar Avatar asked May 11 '12 12:05

Ibrahim Najjar


1 Answers

Maybe something like this:

SELECT
    Books.book_title,
    STUFF
    (
        (
            SELECT 
                ',' +author
            FROM
                book_authors
                JOIN Authors
                    ON book_authors.authorId=Authors.authorId
            WHERE
                book_authors.bookId=Books.bookid
            FOR XML PATH('')
        )
    ,1,1,'')
FROM
    Books

EDIT

It is hard to say with out you data. Does this work:

DECLARE @Table1 TABLE(ID INT)
DECLARE @Table2 TABLE(Name varchar(100),ID INT)

INSERT INTO @Table1 VALUES(1),(2)
INSERT INTO @Table2 VALUES('test1',1),('test2',1),('test3',2),('test4',2)

SELECT
    t1.ID,
    STUFF
    (
        (
            SELECT 
                ',' +t2.Name
            FROM
                @Table2 AS t2
            WHERE
                t1.ID=t2.ID
            FOR XML PATH('')
        )
    ,1,1,'')
FROM
    @Table1 AS t1
like image 174
Arion Avatar answered Sep 20 '22 06:09

Arion