【问题标题】:mysql - php - Need to get only the latest record from a self referencing datamysql - php - 只需要从自引用数据中获取最新记录
【发布时间】:2013-05-17 10:51:27
【问题描述】:

嗨, 我需要一些关于 SQL 的帮助。附上我桌子的图片。

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

同样,119 的 2 条记录进行另一次对话。

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

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

现在是复杂的一点。我想要每个对话中唯一的最新记录(基于 datetimecreated)。

按照脚本创建此表。

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

【问题讨论】:

    标签: php mysql codeigniter self-referencing-table


    【解决方案1】:

    你想要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】:

      使用 ORDER BY 日期时间 ASC/DESC

      这将按顺序对您的结果进行排序,然后将 LIMIT 1 添加到查询的末尾,以仅获取列表中的第一条记录。

      【讨论】:

      • 我希望从每组转换中获取最新记录。
      • 嗯,好吧,按日期排序,然后使用 GROUP BY 你的 id,在你的例子中是 7
      【解决方案3】:

      这是你的SQl Fiddle,没有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)
      

      【讨论】:

        猜你喜欢
        • 2014-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2011-09-18
        • 2017-11-24
        相关资源
        最近更新 更多