I am trying to implement a messaging system for the application I am currently working at. The messages are stored in a table:
CREATE TABLE `message` (
`MessageID` BIGINT(20) NOT NULL AUTO_INCREMENT,
`Thread` BIGINT(20) NOT NULL,
`From` BIGINT(20) NOT NULL,
`To` BIGINT(20) NOT NULL,
`DateTime` DATETIME NOT NULL DEFAULT '2012-01-01 00:00:00',
`Content` TEXT NOT NULL,
PRIMARY KEY (`MessageID`),
CONSTRAINT `FK_messageTo` FOREIGN KEY (`To`) REFERENCES `team` (`TeamID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_messageFrom` FOREIGN KEY (`From`) REFERENCES `team` (`TeamID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_thread` FOREIGN KEY (`Thread`) REFERENCES `thread` (`ThreadID`) ON DELETE CASCADE ON UPDATE CASCADE
);
Thread is another table that stores conversation threads, basically pairs of users.
When a user views a conversation they’ve had with somone, they should only be displayed the most recent, say, 10 messages. More messages are displayed on demand (click of a button, whatever). I am unsure what the most efficient way of pooling the database is in this case.
-
Taking out the whole thread each time and cutting it down obviously defeats the point.
-
Have a query along the lines of:
SELECT * FROM message WHERE (to = {party1} AND `from` = {party2}) OR (to = {party2} AND `from` = {party1}) ORDER BY messageID DESC LIMIT {start}, {length}
where expressions like {name} are variables. I am unsure how LIMIT works here and if will be faster than my first method.
- A third option would be to add another field (index) that is incremented within the thread (as the primary key in the message table is incremented whenever a new message is added anywhere in the system).
Here one suggestion that comes to my mind after seeing your requirement is:
Lets say if you have to display 10 conversations at a time and if user wants to see more he will be provided a button to see next 10 conversations.
So what you can do is,first select the first 10 conversations and store the last conversations id number in some variable in the front end application.
When user clicks on a button to see next 10 conversations,then again send a query to sql engine with rang lastid+10. That is:
Also make sure you have proper indexes on the tables.