mariadb 如何在保留其他相关信息的同时一次性打印重复列?MySQL

xienkqul  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(109)

| 名字|姓氏|作者ID|编写的书籍|
| - -|- -|- -|- -|
| 巴比|尤因|一百零一|如何疏通堵塞的耳朵|
| 巴比|尤因|一百零一|最后一班去克拉克斯维尔的火车|
| 巴比|尤因|一百零一|逃离吉利根岛|
| 巴比|尤因|一百零一|如何疏通堵塞的耳朵|
| 红色|斯凯尔顿|一百零二|史密斯先生去华盛顿|
| 红色|斯凯尔顿|一百零二|如何进行数字签名|
| 红色|斯凯尔顿|一百零二|修复计算机|
| 红色|斯凯尔顿|一百零二|小熊队赢了!|
在此方案中,我希望'Bobby Ewing 101'只显示一次,而“Books Written”列将打印出每个不同的帐面价值。因此,如果可能的话,它应该如下所示:

| First Name | Last Name | Author ID | Books Written                 |
|------------|-----------|-----------|-------------------------------|
|  Bobby     | Ewing     |       101 |  How to Grow Tomatoes         |
|            |           |           |  Last Train to Clarksville    |
|            |           |           |  Escape from Gilligans Island |
|            |           |           |  How to Grow Cucumbers        |
|  Red       | Skelton   |       102 |  Mr. Smith Goes to Washington |
|            |           |           |  How to Digitally Sign        |
|            |           |           |  Fixing Computers             |
|            |           |           |  Cubs Win!                    |

下面是我的SELECT语句:

SELECT a.firstName AS 'First Name', a.lastName 'Last Name', a.authorID AS 'Author ID', b.title AS 'Books Written' 
FROM Author a, WrittenBy w, Book b 
WHERE b.ISBN = w.ISBN AND w.authorID = a.authorID;
rnmwe5a2

rnmwe5a21#

您可以使用MySQL GROUP_CONCAT函数对“Books Written”字段进行聚合,如下所示:

SELECT a.firstName                          AS `First Name`, 
       a.lastName                           AS `Last Name`, 
       a.authorID                           AS `Author ID`, 
       GROUP_CONCAT(b.title SEPARATOR '\n') AS `Books Written`
FROM       Author a 
INNER JOIN WrittenBy w 
        ON w.authorID = a.authorID
INNER JOIN Book b
        ON b.ISBN = w.ISBN
GROUP BY a.firstName,
         a.lastName,
         a.authorID

注意:最好将JOIN操作显式化,并在MySQL中对字段名使用反勾号。

相关问题