Possible recursive solution in MySQL to find comments and replies -


not (possibly) recursive solution, i've encountered problem many times. have table called post_comments looks this:

table: post_comments comment_id    comment_text    user_id    parent_id    type 1                'x'             1           15         1 2                'hi'            2            1         2 3                'yo'            5           15         1 4                'hey'           3           1          2 

basically, type tinyint(1) column. if type 2, means reply comment. if type 1, it's comment post. this:

post: 'texttexttextloremipsmu' uuser comments:      'x' <- type 1          'yo' <- type 2, reply 'x' 

if type 2, means parent_id references comment_id in table post_comments. if it's 1, references post in posts table posts (not shown). need sql query can find comments , replies post (i.e.) post_id = 15. needs return union group by pseudo-code is:

select comment_id, type post_comments parent_id = 15 , type = 1 union group comment_id select comment_id post_comments parent_id = comment_id order likes or date_posted (some arbitrary field) 

to (basically first row comment , below replies comment , continues until replies listed , there no other comments)

comment_id   type 1             1 2             2 4             2 3             1 

how can accomplish in 1 query? or there wrong database structure causing problem? maximum nesting possible 1 (as in there no replies replies, replies comments)

this work:

select *  (select comment_id new_id,comment_text `post_comments` `type` = 1) parent union select *  (select parent_id new_id,comment_text `post_comments` `type` = 2) child order `new_id` 

what did consider each type separate table , join them based on common id, had create new column (new_id) able use sorting, have issue standing comment came first, recommend you'd add in created_on_date column you'd use second index sort with.

p.s. took me hour :d


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -