使用 group_concat 在单个查询中使用多个文本字段
我是 MySQL 的新手,正在使用它来管理书籍数据库。每本书除了其标准数据和描述之外,还有一些杂项文本字段,这可能取决于该书。例如,一本书可能有一些评论、链接等。
我想将它们存储在一个包含 book_id、字段类型(例如评论)和字段内容的表中。
现在,我的问题是,当我获取一本书的所有数据时,我想优化查询。通过第二个查询获取所有附加文本字段数据就足够简单了。但是,如果我使用 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, 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GROUP_CONCAT 通常是使报告变得更容易的绝佳方法。但对于包含大量文本的字段,这很容易导致数据被正确截断(例如在 1024 个字符后被截断,具体取决于您的 my.cnf 设置 group_concat_max_len )。更糟糕的是,如果 GROUP_CONCAT'ed 的字段是 BLOB 类型(TEXT、LONGTEXT 等),则会有大量 RW 作为临时表写入磁盘。但是,如果您 GROUP_CONCAT'ing 的字段是 VARCHAR 或 INT,则您可以仅使用单个查询而不是多个查询直接从索引缓存数据创建大量报告,这可能会提高性能。
PS
如果我对 MySQL 如何缓存聚合查询中的数据有误,请纠正我。
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
PS correct me if I'm wrong about how MySQL caches data from aggregated queries.