我试图获取每个msisdn的最新行,我将传递给IN子句
这是我的表结构
CREATE TABLE `cell_volume_details` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`date_time` bigint(20) DEFAULT NULL,
`cell_id` int(11) DEFAULT NULL,
`volume` bigint(20) DEFAULT NULL,
`dn` int(11) DEFAULT NULL,
`cg_key` varchar(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO CHARSET=latin1;
这是我的查询
SELECT DISTINCT dn, cell_id as cell, cg_key
FROM cell_volume_details WHERE dn IN
(55484522680, 55484522794, 55484522289,
55484522995, 55484522840, 55484522106,
55484522610) ORDER BY id DESC;
这是结果
+-------------+-------+--------+
| dn | cell | cg_key |
+-------------+-------+--------+
| 55484522106 | 4181 | cg1 |
| 55484522106 | 21183 | cg1 |
| 55484522840 | 17369 | cg11 |
| 55484522289 | 1222 | cg2 |
| 55484522106 | 32181 | cg1 |
| 55484522106 | 32183 | cg1 |
| 55484522794 | 27363 | cg5 |
| 55484522995 | 24219 | cg3 |
| 55484522794 | 21368 | cg5 |
| 55484522794 | 40367 | cg5 |
| 55484522794 | 10367 | cg5 |
| 55484522289 | 1229 | cg2 |
| 55484522289 | 17228 | cg2 |
| 55484522289 | 1227 | cg2 |
| 55484522794 | 45368 | cg5 |
| 55484522610 | 6018 | cg9 |
| 55484522680 | 2373 | cg2 |
| 55484522610 | 1158 | cg9 |
| 55484522610 | 3151 | cg9 |
| 55484522794 | 13369 | cg5 |
| 55484522610 | 3153 | cg9 |
| 55484522289 | 1228 | cg2 |
| 55484522840 | 17369 | cg2 |
| 55484522610 | 14163 | cg9 |
| 55484522610 | 14169 | cg9 |
| 55484522794 | 8361 | cg5 |
| 55484522680 | 17373 | cg2 |
| 55484522794 | 8362 | cg5 |
| 55484522289 | 1225 | cg2 |
| 55484522794 | 10368 | cg5 |
| 55484522794 | 8367 | cg5 |
| 55484522680 | 17371 | cg2 |
| 55484522680 | 27362 | cg2 |
| 55484522995 | 24217 | cg3 |
| 55484522794 | 43369 | cg5 |
| 55484522794 | 10365 | cg5 |
| 55484522840 | 17369 | cg13 |
| 55484522610 | 1152 | cg9 |
| 55484522794 | 8368 | cg5 |
| 55484522995 | 24218 | cg3 |
+-----------+-------+--------+
我无法找到错误。我在桌子上有8千万条记录,当我进行GROUP BY时,它变得很慢,任何人都请帮帮我
答案 0 :(得分:1)
如果你想要dn的最后一行,你应该通过cell_volume_details选择具有max(id)group的行
select dn, cell_id as cell, cg_key
FROM cell_volume_details
where id in (
select max(id) from cell_volume_details WHERE dn IN
(55484522680, 55484522794, 55484522289,
55484522995, 55484522840, 55484522106,
55484522610)
)
答案 1 :(得分:1)
select *
from
(
select s.*,
if(s.dn <> @p,@rn:=1,@rn:=@rn+1) rn,
@p:=s.dn
from
(
SELECT id,dn, cell_id as cell, cg_key
FROM cell_volume_details
WHERE dn IN
(55484522680, 55484522794, 55484522289,
55484522995, 55484522840, 55484522106,
55484522610)
) s
, (select @rn:=0 ,@p:=0) rn
order by s.dn,s.id desc
) t
where t.rn = 1