2017-12-02 16 views
0

2つのテーブルで最大値を取得し、4つの異なる列に表示する必要があります。摂氏| |ハムfecha_temp |2つのテーブルの最大値を取得するクエリmysql

Table: temperaturas 
Columns: 
id_temp int(11) AI PK 
celsius_temp decimal(10,0) 
fah_temp decimal(10,0) 
fecha_temp datetime 

Table: humedad 
Columns: 
id_hum int(11) AI PK 
hum_hum float 
fecha_hum datetime 

fecha_hum私​​はこのクエリを試みたが、そんなに

select t.celsius_temp as celsius, h.hum_hum, t.fecha_temp, h.fecha_hum from 
temperaturas t 
inner join humedad h on h.hum_hum <=(select max(h.hum_hum) from humedad h) 
where t.celsius_temp<=(select max(t.celsius_temp) from temperaturas t) and 
t.fecha_temp between '2017-12-01' and '2017-12-05' 
order by t.celsius_temp, h.hum_hum desc limit 1; 

おかげで動作しません

+1

最大値の列は? – Imran

答えて

1

期間内の各テーブルの最大値は次のとおりです。

SET @start_date = '2017-12-01'; 
SET @end_date = '2017-12-01'; 
SELECT MAX(t.celsius_temp) INTO @tmax FROM temperaturas t 
    WHERE t.fecha_temp BETWEEN @start_date AND @end_date; 
SELECT MAX(h.hum_hum) INTO @hmax FROM humedad h 
    WHERE t.fecha_hum between @start_date AND @end_date; 

ますそれらを両方とも1つのテーブルに入れることができます:

SELECT @tmax, @hmax; 

最大の温度または最大の湿度に達した日付を知りたい場合は、同じ値で複数の日付がある可能性があるため、ややこしいことです。あなたは、単一のクエリとしてこれを書くことができますが、私はむしろ、上記のクエリを使用して、実行したい:

SELECT * from temperaturas t where t.celsius_temp = @maxt; 
SELECT * from humedad h where h.hum_hum = @maxh; 

は、温度が複数の日付で同じである場合、これは複数の行を持つことができ、覚えておいてください。これを1つのテーブルにどのように組み込むのが簡単な感覚的な方法はありません。

1日に複数の測定値があり、各日の最高温度/湿度を検索する場合は、グループ化機能を使用します。あなたは、このようなタイムスタンプの日付()functioに参加することができます:あなたが唯一のテーブルにデータを持っている可能性があるの日付を持っている可能性があるため、ここで

SELECT coalesce(date(t.fecha_temp), date(h.fecha_hum)), 
    MAX(t.celsius_temp) as celsius, 
    MAX(h.hum_hum) as humibity 
FROM temperaturas t 
OUTER JOIN humedad h on date(t.fecha_temp) = date(h.fecha_hum) 
WHERE coalesce(date(t.fecha_temp), date(h.fecha_hum)) 
    between @start_date and @end_date 
GROUP BY coalesce(date(t.fecha_temp), date(h.fecha_hum)) 
ORDER BY coalesce(date(t.fecha_temp), date(h.fecha_hum)) 

coalesce()機能が必要です。

このジョインは、大量のデータがある場合は効率的ではありません。この場合、グループ関数の結果を使用してテンポラリテーブルを作成し、日付ごとに1行だけにジョインすることができます。

関連する問題