doushi1473 2013-05-17 10:51
浏览 35
已采纳

mysql - php - 需要从自引用数据中获取最新记录

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 );
  • 写回答

3条回答 默认 最新

  • duanpi2033 2013-05-17 11:07
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题