I’m assuming that StackOverflow’s question and answer (or even FB’s wall messages) can be mimicked by the following model:
TABLE: message
==================================================================
| message_id | parent_message_id | message | timestamp |
==================================================================
| 1 | 0 | Hi | 100 |
| 2 | 1 | hello | 200 |
| 3 | 1 | hello back to you | 300 |
| 4 | 0 | How are you? | 150 |
| 5 | 4 | Good. You? | 200 |
| 6 | 4 | Good, too. | 250 |
------------------------------------------------------------------
Questions:
- Is this a good way to do parent-child relationships for such messages? It could be split into 2 tables, but the child table would look exactly like the parent table + a foreign key. So I think one table is good enough.
- How do I query: get a list of all parent messages and the first 4 responses to them?
- How do I query: given a parent message id, get a list of the next 10 responses after the first 4?
- How do I query: get the last 10 messages of a particular discussion thread (similar to FB’s messages where you only see the last x-number of messages)?
- How do I query: get the second to the last 10 messages of a particular discussion thread (again, similar to FB’s messages when you scroll up and it shows you more of the previous messages)?
If the DB design concept is inherently wrong, please let me know.
Below is the DB layout for SO.
As you can see in the first table
postsyour idea is exactly what SO does.A query to get a question and its answers would be:
This will put the question at the top and the answers below it.
Stackoverflow data structure: