Here’s the situation. I have two tables:
- users (registered users of the
website), - messages (personal messages they sent between each other)
The messages table has these columns (just the important ones):
- id,
- sender (id of user who sent the
message), - receiver id of user to whom
the message was sent), - reply_to (id of a message to which this message is
reply to, can be NULL)
What I need to do is construct a SELECT query that will select a complete conversation between 2 users. I.e. if user A replies to message sent from user B and the user B replies back to the message, I would like to get three rows like this:
- message03: reply to the message02
- message02: reply to the message01
- message01 from user A to user B
I’m sure that it is possible to construct such a SELECT query based on the reply_to field but I have never done something like it before so I need a little help.
The SELECT query should be for MySQL database.
Actually you’re incorrect: with ANSI SQL this isn’t possible. Certain databases with vendor extensions (eg Oracle’s
CONNECT BY) may be able to do what you want but not plain old SQL.My advice? Change your data so enable an easier solution.
In this case, give each message a conversation_id. If the user posts a new message, give that a new (currently unused) value. If they reply, keep the conversation_id of the message being replied to.
Then querying the data becomes trivial.