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 に答える