开发者

Too many queries for selecting hierarchical comments

I have this MySQL table but it takes one query for one comment. If there are 20 comments i开发者_Go百科t makes 20 queries to show the page. Is there any solution? Is it possible to write a MySQL-side function in order to reduce the query size to one?


In addition to storing parent, also store (in a separate column) an id for what item/article the comment was posted on. Then just query for all of the comments with the same item id, and construct the hierarchy after getting the DB rows.


You could look into Joe Celko's 'Nested Set' algorithm. It provides very efficient 'one-query' retrieval for hierarchical datasets, but there is always a cost, and the cost is that it requires a bit more legwork when you insert into the table.

For high-write activity, I'm not sure I'd go for it personally.

I'd be more likely to just slam it into memcache, and invalidate the cache when someone posts to a specific thread.

Either of these solutions though, is way better than running 20 queries to retrieve 20 comments.


You can do it in a single call from php to mysql if you use a stored procedure. I'd stick to the adjacency list vs. the nested set implementation as you'll only experience more pain using it.

see here: Generating Depth based tree from Hierarchical Data in MySQL (no CTEs)

Hope this helps :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜