2016-11-11 3 views
0

私は、特定のコードのための最大の日付のmax時間でその行を最後の行を選択する必要があり選択maxは、mysqlの

date(int), time(int), code(int), title(varchar) 

のようなテーブルを持っています。表が非常に大きい、と私は、クエリ

テーブル

date  time code title 
20161110 1045 5522 plant1 
20161110 1045 5522 plant1 
20161110 1100 5522 plant1 
20161111 1030 5522 plant1 
20161111 1045 5522 plant1 

のようにpossbile少ないリソースを使用する必要があります私は1つの行

20161111 1045 5522 plant1 

を得ることを期待し、それが私の安っぽいSQL

select * 
from ep_ft_consumptions_experimental as cons 
    (inner join (select max(date) as md 
       from ep_ft_consumptions_experimental 
       where plant_code=5522 
        and d1=1 
       ) dr 
     on cons.date = dr.md) 
    (inner join (select max(time) as mt 
       from ep_ft_consumptions_experimental 
       ) tr 
     on cons.time = tr.time 
です
+3

あなたの宿題をここにダンプする前に試してみますか? – Mihai

+4

日付と時刻はなぜ別ですか?なぜタイムスタンプではないのですか?あなたは足で自分を撃っている。 – Aus

+0

サンプルテーブルのデータと期待される結果、および書式付きテキストを追加します。現在のクエリの試行を表示し、何が間違っているのかを説明してください。任意の主キー、またはインデックス? – jarlh

答えて

1

非常に簡単です。 ORDER BYLIMIT 1を使用してください:効率については

select cons.* 
from ep_ft_consumptions_experimental as cons 
where cons.code = 5522 
order by cons.date desc, cons.time desc 
limit 1 ; 

を、あなただけが存在していないものを持っている場合(code, date, time)に複合インデックスを追加する必要があります。

+0

シンプルで働きがいのあるthanx – XSigno

+1

この複合インデックスはさらに優れています: 'INDEX(コード、時間)。 –