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

标签 php mysql codeigniter self-referencing-table

enter image description here

嗨, 我需要一些有关 SQL 的帮助。附件是我的 table 的图片。

如果您看到 rootmessageid 列,则有 4 条 99 的记录。这 4 者构成了一次完整的对话。

类似地,119的2条记录构成了另一个对话。

116、117、118 是单消息对话。

现在我需要获取 msgfrom = 7 或 msgto = 7 的所有记录(这是简单的部分)

现在是复杂的部分。我只想要每次对话的最新记录(基于创建的日期时间)。

按照脚本创建此表。

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 );

最佳答案

您想要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

关于php - mysql - php - 只需要从自引用数据中获取最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607230/

相关文章:

mysql - mariadb中的json路径

php - 为什么我的所有文件都有重复项,末尾为 '~'?

javascript - 如何在ajax中格式化货币

php - 批量密码哈希 PHP-LOGIN 项目代码

javascript - 如何在没有任何提交按钮的情况下动态显示基于从下拉列表中选择的年份的记录

连接 SQL 失败时的 PHP 脚本

php在同一页面显示查询结果

PHP/MYSQL排名代码导致PHP/MYSQL加载页面缓慢

javascript - 创建弹出浏览器小部件

sql - 从结果集中的子查询返回记录数