使用如下表格:
idx type dat
0 a foo1
1 b foo2
2 c foo3
3 a foo4
4 b foo5
5 c foo6
6 a foo7
7 b foo8
8 c foo9
我如何获得每种类型的第一个和最后一个数据:
例如:
a foo1 foo7
b foo2 foo8
c foo3 foo9
我已经尝试过这个查询,但它的速度很慢,即使是idx和type上的索引:
select mins.type, mins.dat, mytable.dat from mytable
--get the maximums
inner join
(select max(idx) as maxidx from mytable group by type) as a
on a.maxidx = mytable.idx
--join the maximums to the minimums
inner join
--get the minimums
(select * from mytable inner join (select min(idx) as minidx from mytable group by type) as b
on b.minidx = mytable.idx ) as mins
on issues.type = mins.type
在issues.type = mins.type上的连接似乎正在减慢它的速度,因为mins.type是派生的而不是索引的?
答案 0 :(得分:1)
使用mysql的GROUP BY
的“时髦”功能,而聚合其他列,只返回该组的第一行行。然后问题就是使用此功能在 之前将行放入正确的顺序,通常使用别名查询。
这种方法避免了任何相关的子查询(每行查询),并且只需要在表上进行两次传递(每个方向对应一个方向):
select x2.type, x2.dat as first_dat, y2.dat as last_dat
from (select *
from (select type, dat
from so8735514
order by 1, 2) x1
group by 1) x2
join (select *
from (select type, dat
from so8735514
order by 1, 2 desc) y1
group by 1) y2 on y2.type = x2.type;
测试代码:
create table so8735514 (idx int, type text, dat text);
insert into so8735514 values
(0, 'a', 'foo1'),
(1, 'b', 'foo2'),
(2, 'c', 'foo3'),
(3, 'a', 'foo4'),
(4, 'b', 'foo5'),
(5, 'c', 'foo6'),
(6, 'a', 'foo7'),
(7, 'b', 'foo8'),
(8, 'c', 'foo9');
输出:
+------+-----------+----------+
| type | first_dat | last_dat |
+------+-----------+----------+
| a | foo1 | foo7 |
| b | foo2 | foo8 |
| c | foo3 | foo9 |
+------+-----------+----------+