1

我遇到了一个问题,我有庞大的数据库,现在我无法进行更改,我需要先处理所有这些数据。问题是下面编写的每个查询大约需要 1-2 分钟。如果有人知道如何进行优化选择,我会应用它。

select distinct x.peerId
,(select max(id) from checkPeer where peerId=x.peerId) as idd 
from checkPeer x where x.id>0 order by x.id desc

有没有办法从下面定义的表中优化这个选择?

CREATE TABLE `checkPeer` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`peerId` varchar(100) COLLATE utf8_bin DEFAULT NULL,
`peerDate` datetime DEFAULT NULL,
`peerUrl` bigint(20) DEFAULT '0',
`peerState` bigint(20) DEFAULT '0',
`peerMessage` varchar(500) COLLATE utf8_bin DEFAULT NULL,
`peerResource` varchar(5000) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `peerId` (`peerId`),
KEY `peerUrl` (`peerUrl`)
) ENGINE=MyISAM AUTO_INCREMENT=688791 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

谢谢!

4

2 回答 2

0

一些直接的建议,删除DISTINCT并尝试以下操作:

select x.peerId, x1.id as idd 
from checkPeer x 
left join
(
    select max(id) id, peerid
    from checkPeer
    group by peerid
) x1
    on x.peerid = x1.peerid
where x.id>0 
order by x.id desc

如果您最终需要更多字段但您说只需要两个字段,则上述方法效果很好,因此您可以尝试:

select peerId, max(id) as idd
from checkPeer 
where id > 0
group by peerid
于 2012-10-04T21:31:17.387 回答
0

为什么不按 peerid 分组并选择 max(id)?

select peerId, max(id) as idd
from checkPeer 
  where id > 0
  group by peerid
  order by id
于 2012-10-04T21:41:19.953 回答