简体   繁体   中英

Return a single MySQL results with multiple values from a row

I'm trying to do a simple search query in php with:

SELECT * FROM `books` NATURAL JOIN `authors` WHERE `books`.`title` LIKE '%$search%

In the returned result I expect the same book title to have more then one author. I would like to display the title just once with multiple authors, and can't seem to find an elegant solution to print the wanted values without doing at least 2 loops with multiple counters like so:

    $last = ""; $i = 0;
while ($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
    $current = $row['title'];
    if ($current != $last) {
        $i += 1;
        $books[$i]['title'] = $current;
        $books[$i]['author'][] = $row['author'];
        $books[$i]['pages'] = $row['pages'];
    } else {
        $books[$i]['author'][] = $row['author'];
    }
    $last = $current;
}

foreach ($books as $book) {
    $return_result .= 'Title:  '  . $book['title']  . '<br />';
    foreach ($book['author'] as $author) {
        $return_result .= 'Author: '  . $author . '<br />';
    }
    $return_result .= 'Pages:  '  . $book['pages']  . '<br />';  
    $return_result .= '<br />';
}

Please tell me if there's a better way to do this, maybe in MySQL ?

The GROUP_CONCAT function will give a delimited list of authors.

SELECT b.title, b.pages, GROUP_CONCAT(a.author)
    FROM books b
        NATURAL JOIN authors a
    WHERE b.title like '%$search%'
    GROUP BY b.title, b.pages;

This can be accomplished with GROUP_CONCAT()

SELECT *, GROUP_CONCAT(`authors`.`author`) AS `authors`
FROM `books` 
NATURAL JOIN `authors` 
WHERE `books`.`title` LIKE '%$search%'
GROUP BY `books`.`title`

Now your list of authors for each book will be comma separated under the field name authors for each book if you want them hyphen separated or another delimiter then use

GROUP_CONCAT(`authors`.`author` SEPARATOR ' - ')

NOTE: Grouping by title is not be the best way to group your search of books as many books can have the same title thus messing up the results. It'd be best to group by ISBN number or some other unique identifier for each book.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM