2

我一直在为此苦苦挣扎。我尝试了所有方法,例如左外连接、分组方式甚至子查询,但都没有成功。这是我的查询。

select star_ident,transition_ident,fix_ident,sequence_num,route_type
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU';  

从上面的结果集中,我需要为给定的 transition_ident 和 star_ident 提取具有最大 sequence_num 的那些行。这是我的查询。

select star_ident,transition_ident,fix_ident,max(sequence_num)
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU'
group by transition_ident,star_ident;

但是上面的查询产生了错误的结果。我什至尝试了连接。

select yt1.star_ident,yt1.transition_ident,yt1.fix_ident
from corept.std_star_leg yt1
left outer join corept.std_star_leg yt2
on (yt1.star_ident = yt2.star_ident and yt1.transition_ident=yt2.transition_ident and      yt1.sequence_num < yt2.sequence_num)
where yt1.airport_ident='KMMU' and yt1.data_supplier='J'
and yt2.airport_ident='KMMU' and yt2.data_supplier='J' and yt2.star_ident is null;

但我最终得到了零行。请提供一种有效的方法来执行此操作。我需要为 13K 条目运行此查询。谢谢。

4

3 回答 3

2

您的选择中有非聚合列,它们不属于分组依据。

来自 MYSQL 文档

MySQL extends the use of `GROUP BY` so that the select list can refer to nonaggregated
columns not named in the GROUP BY clause. You can use this feature to get better
performance by avoiding unnecessary column sorting and grouping. However, this is 
useful primarily when all values in each nonaggregated column not named in the 
GROUP BY are the same for each group. The server is free to choose any value from 
each group, so unless they are the same, the values chosen are indeterminate.

因此,要获得正确的结果,请将 select 的所有列添加到 group by

编辑

select b.* 
from 
corept.std_star_leg b
inner join
(select star_ident,transition_ident,max(sequence_num) as seq
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU'
group by star_ident,transition_ident) a
on b.star_ident = a.star_ident and a.transition_ident = b.transition_ident and
b.sequence_num = a.seq;  

希望能帮助到你....

于 2013-04-12T07:03:46.857 回答
1

尝试这个:

SELECT *
FROM
  (SELECT *
   FROM table1
   ORDER BY seqno DESC) tmp
GROUP BY `star_ident`,
         `trans`

这是sqlfiddle

于 2013-04-12T08:20:34.273 回答
0

按 start_ident 删除组

select star_ident,transition_ident,fix_ident,max(sequence_num)
from corept.std_star_leg where data_supplier='J' and airport_ident='KMMU'
group by transition_ident
于 2013-04-12T07:01:45.707 回答