How to show the data repeated only once?

Asked

Viewed 257 times

3

Well, I have the following problem in Mysql: I created two tables a table of books and another table of authors. Well, I need to show the name of the book with their respective authors, but have some books that have more than 1 author or using the following SQL:

select l.titulo_livro, a.nome_autor, a.id_autor from tb_livros as l 
join tb_autores as a
where l.id_livro = a.id_livro_escrito;

I get the following result:

Resultados

Is there any way to ensure that the name of the book is not repeated and that the names of the authors of the same book are joined?

2 answers

7

I believe you’re looking for the job GROUP_CONCAT:

select l.id_livro, 
    MIN(l.titulo_livro), 
    GROUP_CONCAT(a.nome_autor),
    GROUP_CONCAT(a.id_autor)
from tb_livros as l join tb_autores as a
    on (l.id_livro = a.id_livro_escrito)
group by l.id_livro

It is also possible to group by titulo_livro if your model ensures that there are no books with the same title (i.e., titulo_livro is a unique key in tb_livro), but the solution with the identifier is more robust.

The function MIN is not strictly required in Mysql since titulo_livro is functionally dependent of id_livro. That said, for compatibility reasons with other banks I chose not to use directly a column that was not listed in the clause group by. Newer versions of Mysql even expose a function ANY_VALUE to deal with this kind of situation.

  • Our dear, thank you very much.

  • Pq needed to use MIN ?

  • I updated the response to comment on the use of MIN.

  • If the answer has properly solved your problem please do not forget to accept it.

  • I think you forgot! rsrs

0

With a distinct it will eliminate the same results:

   select distinct l.titulo_livro, a.nome_autor, a.id_autor from tb_livros as l 
join tb_autores as a
where l.id_livro = a.id_livro_escrito;
  • A book can have several authors. He wants the authors to be concatenated to each line of book.

  • I had already tested with the distinct, but the result remains the same

  • the identifier of the authors table is id_author or id_book_written? ?

  • It already worked, Thanks for the help C:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.