将查询与行表合并的SQL查询

时间:2013-05-26 10:57:09

标签: sql vb.net ms-access-2007

我有以下数据库结构

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这包括GROUP BY的{​​{1}}:

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 中的SEPARATOR。此外,这个答案假定MySQL。