MySQL - 连接2个表时选择第二个表中的最后一个条目

时间:2015-05-22 22:31:49

标签: mysql inner-join

当我进行内部联接时,我有2个表事务和trans_comments它返回第一个条目,我想要做的是显示事务表中的地址和状态以及输入的最后一个注释和来自trans_comments表的日期< / p>

这就是我得到的东西

SELECT t.address, t.status, c.time, c.comment
FROM transactions t
INNER JOIN trans_comments c ON c.transactionId = t.transactionId
WHERE STATUS LIKE  '%Listing%'
GROUP BY t.address DESC

我错过了什么?

以下是表格的布局:

`transactions` (
  `transactionId` int(11) NOT NULL AUTO_INCREMENT,
  `address` varchar(45) NOT NULL,
  `listing_agent` varchar(65) DEFAULT NULL,
  `status` varchar(45) NOT NULL,
  `notes` varchar(100) DEFAULT NULL,
  `file_type` varchar(25) NOT NULL,
  `system` varchar(25) DEFAULT NULL,
  PRIMARY KEY (`transactionId`)      
)ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=41 ;

`trans_comments` (
  `commId` int(11) NOT NULL AUTO_INCREMENT,
  `transactionId` int(11) NOT NULL,
  `comment` blob NOT NULL,
  `commentBy` varchar(45) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`commId`),
  KEY `transactionId` (`transactionId`)
)ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=101 ;

由于

1 个答案:

答案 0 :(得分:-1)

SELECT t.address, t.status, c.time, c.comment
FROM transactions t
INNER JOIN 
  (SELECT c1.*
   FROM trans_comments c1
   LEFT JOIN trans_comments c2
   ON c1.transactionId = c2.transactionId 
     AND c1.`time` < c2.`time` 
   WHERE c2.commId IS NULL
  ) c 
ON c.transactionId = t.transactionId
WHERE STATUS LIKE  '%Listing%'