开发者

Multiple text fields in a single query using group_concat

I'm new to MySQL, and am using it to manage a database of books. Each book has, in addition to its standard data and description, some miscellaneous text fields, 开发者_Python百科which may depend on the book. For example a book might have a few reviews, links, etc.

I thought I'd store these in a table with the book_id, the field type (for example review), and the field contents.

Now, my problem is that when I obtain all the data for a single book, I'd like to optimize the query. It'd be simple enough to get all the additional text field data with a second query. However, would there be a significant performance gain if I were to use group_concat to give me all the book information, including these additional text fields, in a single query?

This means I'd also have to make sure my separator character is escaped, and I'd have to unescape it after obtaining the data. Which approach would work better for me?

Thanks!


GROUP_CONCAT is normally an excellent way of making reporting easier. But for fields containing a lot of text, this will easily lead to right truncated data (chopped off after e.g. 1024 characters depending on you my.cnf setting group_concat_max_len ). Worse, if the field(s) that are GROUP_CONCAT'ed is of type BLOB (TEXT, LONGTEXT etc) there will be a lot of RW to disk as temptables. However if the fields that you GROUP_CONCAT'ing are VARCHAR or INT, you may create huge reports straight from index cached data using only a single query instead of multiple, which may be a performance boost.

example

SELECT 
    B.bookID, 
    B.bookTitle, 
    B.isbn, 
    GROUP_CONCAT(
        CONCAT(
            (IFNULL(R.review, "no reviews of this book")), 
            R.revierName)
        ORDER BY R.stars 
        SEPARATOR "<br />"
    ) AS reviews
FROM books B
LEFT JOIN reviews R ON (B.bookID = R.bookID)
;

PS correct me if I'm wrong about how MySQL caches data from aggregated queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜