Mysql 将结果集的多行合并为一行
我有这样一个问题:Mysql 将结果集的多行合并为一行,mysql,sql,resultset,Mysql,Sql,Resultset,我有这样一个问题: SELECT DISTINCT obl_books.book_id, obl_books.long_title, obl_books.short_title, obl_authors.first_name FROM obl_books, obl_authors, books_authors WHERE obl_books.book_id = b
SELECT DISTINCT
obl_books.book_id,
obl_books.long_title,
obl_books.short_title,
obl_authors.first_name
FROM
obl_books,
obl_authors,
books_authors
WHERE
obl_books.book_id = books_authors.book_id
AND
obl_authors.author_id = books_authors.author_id
AND
obl_books.short_title = 'SQL'
Book1| SQL REFERENCE | author1 | author2 | author3
它为每个作者提供了两个单独的行。我希望它像这样排成一行:
SELECT DISTINCT
obl_books.book_id,
obl_books.long_title,
obl_books.short_title,
obl_authors.first_name
FROM
obl_books,
obl_authors,
books_authors
WHERE
obl_books.book_id = books_authors.book_id
AND
obl_authors.author_id = books_authors.author_id
AND
obl_books.short_title = 'SQL'
Book1| SQL REFERENCE | author1 | author2 | author3
如何直接在SQL查询中或通过对ResultSet result执行某些操作来实现它?好心的导游。请告诉我没有任何PLSQL机制。取决于哪个rdbms,但您可以尝试
SELECT DISTINCT obl_books.book_id||obl_books.long_title|| etc...
或者在帮助中查找“Concat()”取决于哪个rdbms,但您可以尝试
SELECT DISTINCT obl_books.book_id||obl_books.long_title|| etc...
或者在帮助中查找“Concat()”如果您使用的是MySQL,请尝试以下操作:
SELECT DISTINCT
obl_books.book_id,
obl_books.long_title,
obl_books.short_title,
GROUP_CONCAT(obl_authors.first_name, ',')
ETC...
如果您使用的是MySQL,请将分隔符(逗号)更改为您想要的任何分隔符
SELECT DISTINCT
obl_books.book_id,
obl_books.long_title,
obl_books.short_title,
GROUP_CONCAT(obl_authors.first_name, ',')
ETC...
根据需要更改分隔符(逗号)- 使用
代替旧的SQL-89隐式JOINJOIN
语法WHERE
- 删除
DISTINCT
- 添加
分组依据
- 用于连接一列中的所有名称:
SELECT b.book_id, b.long_title, b.short_title, GROUP_CONCAT(a.first_name ORDER BY a.first_name SEPARATOR ', ' ) AS first_names FROM obl_books AS b JOIN books_authors AS ba ON b.book_id = ba.book_id JOIN obl_authors AS a ON a.author_id = ba.author_id WHERE b.short_title = 'SQL' GROUP BY b.book_id, b.long_title, b.short_title ;
- 使用
代替旧的SQL-89隐式JOINJOIN
语法WHERE
- 删除
DISTINCT
- 添加
分组依据
- 用于连接一列中的所有名称:
SELECT b.book_id, b.long_title, b.short_title, GROUP_CONCAT(a.first_name ORDER BY a.first_name SEPARATOR ', ' ) AS first_names FROM obl_books AS b JOIN books_authors AS ba ON b.book_id = ba.book_id JOIN obl_authors AS a ON a.author_id = ba.author_id WHERE b.short_title = 'SQL' GROUP BY b.book_id, b.long_title, b.short_title ;