gpt4 book ai didi

mysql - 按组类型加入第一个和最后一个记录?

转载 作者:行者123 更新时间:2023-11-29 00:50:35 25 4
gpt4 key购买 nike

像这样的表格:

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 和类型上有索引:

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

on issues.type = mins.type 的加入似乎是导致它变慢的原因,因为 mins.type 是派生的而不是索引的?

最佳答案

使用 mysql 的 GROUP BY 的“funky”功能,聚合其他列,它只返回组的第一行。然后,问题就变成了在使用此功能之前让行按正确的顺序排序,通常是使用别名查询。

这种方法避免了任何相关的子查询(每行查询)并且只需要遍历表两次(每个排序方向一次):

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 |
+------+-----------+----------+

关于mysql - 按组类型加入第一个和最后一个记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com