1

我有以下数据库结构

1 个名为 Books 的表 (BookId,Title) 1 个名为 Authors 的表 (AuthorId,AuthorName) 1 个名为 BooksAuthors (BookID,AuthorID) 的连接表,与其他 2 个表的关系

我正在使用这个查询:

   Select
  Books.BookId,
  Books.Title,
  Authors.AuthorName
From
  (Books Inner Join
  BooksAuthors On BooksAuthors.BookId = Books.BooksId) Inner Join
  Authors On BooksAuthors.AuthorId = Authors.AuthorId

我得到这样的东西:

BookId         Title            AuthorName
001           Title1            Name1
001           Title1            Name2
001           Title1            Name3
002           Title2            Name5
002           Title2            Name6

我想知道是否可以执行返回如下内容的查询:

BookId         Title            AuthorName
001           Title1            Name1;Name2;Name3
002           Title2            Name5;Name6
4

2 回答 2

0

你可以使用GROUP_CONCAT()

SELECT DISTINCT 
  Books.BookId,
  Books.Title,
  GROUP_CONCAT(Authors.AuthorName,'; ')
FROM
  (Books Inner Join
  BooksAuthors On BooksAuthors.BookId = Books.BooksId) Inner Join
  Authors On BooksAuthors.AuthorId = Authors.AuthorId
于 2013-05-26T11:01:16.730 回答
0

这包括GROUP BYfor GROUP_CONCAT

SELECT DISTINCT 
  Books.BookId,
  Books.Title,
  GROUP_CONCAT(Authors.AuthorName SEPARATOR ';')
FROM Books
  INNER JOIN BooksAuthors USING (BookId)
  INNER JOIN Authors USING (AuthorId)
GROUP BY Books.BookId, Books.Title

编辑:修复SEPARATORGROUP_CONCAT此外,这个答案假设 MySQL。

于 2013-05-26T11:16:58.683 回答