mysql structure for posts and comments

倖福魔咒の 提交于 2019-12-01 01:44:36

At a basic level, you would have a table for each type of "thing" in your application. In this case, a table for Posts and a table for Comments. Something as simple as this:

Post
--------
Id
Content
User
DatePosted

Comment
--------
Id
PostId
Content
User
DatePosted

This would create what's called a one-to-many (or zero-to-many, actually) relationship between Posts and Comments, whereby each Post can have zero or more associated Pomments but each Comment can be associated with only one Post.

In your code (which is a whole other subject entirely), to display a Post and its associated Comments there are a couple of things you could do. Assuming you have, as input, the Id of the Post you want, you can get that Post and its Comments:

SELECT `Content`, `User`, `DatePosted` FROM `Post` WHERE `Id` = ?Id
SELECT `Id`, `Content`, `User`, `DatePosted` FROM `Comment` WHERE `PostId` = ?Id

What you do with that resulting data is up to you and how you want to use it in your application. It would come back as two table results, the former of which has one record (if the Post exists) and the latter of which has zero or more records. Naturally, you'll want to check that things exist before trying to use them, etc. (So if the first query returns no results, don't try to continue to display the Post. Just show a default response or an error.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!