我想要的:我遇到了每组最大 n 问题。我的组是一组 TCP 地址,n 是表行插入数据库的日期。
问题:我目前正在获取所有具有与我的 where 子句匹配的 tcp 地址的行,而不是每个 tcp 地址具有最大日期的行。
我正在尝试遵循此示例,但失败了:SQL Select only rows with Max Value on a Column 。
这是我的 table 的样子。
CREATE TABLE IF NOT EXISTS `xactions` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`tcpAddress` varchar(40) NOT NULL,
//a whole lot of other stuff in batween
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=150 ;
示例行是
ID | tcpAddress | ... | date
1 | 192.168.1.161 | ... | 2012-09-12 14:19:39
2 | 192.168.1.162 | ... | 2012-09-12 14:19:40
3 | 192.168.1.162 | ... | 2012-09-12 14:19:41
4 | 192.168.1.162 | ... | 2012-09-12 14:19:42
我尝试使用的 SQL 语句
select yt.id, yt.tcpAddress, yt.analog, yt.discrete, yt.counter, yt.date
from xactions yt
inner join(
select id, tcpAddress, analog, discrete, counter, max(date) date
from xactions
WHERE tcpAddress='192.168.1.161' OR tcpAddress='192.168.1.162'
group by date
) ss on yt.id = ss.id and yt.date= ss.date
最佳答案
您需要按 tcpAddress 进行分组,而不是按日期进行分组。
并通过 tcpAddress 加入,而不是 id。
select yt.id, yt.tcpAddress, yt.analog, yt.discrete, yt.counter, yt.date
from xactions yt
inner join (
select tcpAddress, max(date) date
from xactions
where tcpAddress in ('192.168.1.161', '192.168.1.162')
group by tcpAddress
) ss using (tcpAddress, date);
此外,您不需要在派生表中选择任何额外的列 - 只需选择 tcpAddress 和 max(date)。
关于sql - 按 TCP 地址划分的最大日期组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15420843/