[英]query to get max value in two tables mysql
我需要在兩個表中獲取最大值並以四列差異顯示。 攝氏| 嗡嗡聲 fecha_temp | fecha_hum
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
我嘗試了此查詢,但不起作用
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;
非常感謝
該期間內每個表的最大值為:
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;
您可以將它們都放入一個表中,以執行以下操作:
SELECT @tmax, @hmax;
如果您想知道達到最高溫度或最高濕度的日期,那會有些棘手,因為您可能有多個具有相同值的日期。 您可以將其編寫為單個查詢,但我寧願使用上述查詢,然后運行:
SELECT * from temperaturas t where t.celsius_temp = @maxt;
SELECT * from humedad h where h.hum_hum = @maxh;
請記住,如果溫度在多個日期相同,則可能會有多行。 沒有簡單明智的方法將其合並到一個表中。
如果您每天進行多次測量,並且每天都在尋找最高溫度/濕度,那么您想使用“分組依據”功能。 然后,您可以像這樣加入時間戳的date()函數:
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()
函數是必需的,因為您可能具有僅一個表可以包含數據的日期。
如果您有大量數據,則這種聯接效率不高,在這種情況下,您可能要考慮使用組函數結果創建臨時表,然后每個日期僅在單行上聯接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.