Question

enter image description here

Hi, I need some help with SQL. Attached is the image of my table.

If you see rootmessageid column there are 4 records of 99s. All these 4 makes one complete conversation.

Similarly the 2 records of 119 makes an other conversation.

116, 117, 118 are single message conversation.

Now I need to get all the records where msgfrom = 7 or msgto = 7 (this was the easy part)

Now the complicated bit. I want the only the latest record (based on datetimecreated) from each conversation.

Following the script to create this table.

CREATE TABLE IF NOT EXISTS `selectioncommunication` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `comactionid` int(11) NOT NULL,
  `usercomment` varchar(2048) DEFAULT NULL,
  `msgfrom` int(11) NOT NULL,
  `msgto` int(11) NOT NULL,
  `projectid` int(11) NOT NULL,
  `parentmessageid` int(11) NOT NULL,
  `datetimecreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `rootmessageid` int(11) NOT NULL,
  `isread` tinyint(1) NOT NULL DEFAULT '0',
  `isclosed` tinyint(1) DEFAULT '0',
  `relative_date_time` datetime DEFAULT NULL,
  `consultant_response` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=121 );
Was it helpful?

Solution

You want the groupwise maximum:

SELECT s.*
FROM   selectioncommunication s NATURAL JOIN (
  SELECT   parentmessageid, MAX(datetimecreated) datetimecreated
  FROM     selectioncommunication
  WHERE    msgfrom = 7 OR msgto = 7
  GROUP BY parentmessageid
) t
WHERE  s.msgfrom = 7 OR s.msgto = 7

OTHER TIPS

use ORDER BY datetime ASC/DESC

this will sort your results in order then add LIMIT 1 to the end of your query to only get the first record in your list.

Here is your SQl Fiddle without Join

SELECT *
FROM selectioncommunication k
WHERE datetimecreated = (SELECT
                           MAX(datetimecreated)
                         FROM selectioncommunication s
                         WHERE s.rootmessageid = k.rootmessageid
                         GROUP BY s.rootmessageid
                         ORDER BY s.id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top