查询两个表中获得最大的价值MySQL的

问题描述:

我需要在四分型动物在两个表中的最大值和显示。 Celsius |嗯| fecha_temp | fecha_hum查询两个表中获得最大的价值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 

我尝试这个查询,但不工作

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

每个表的期间的最大值为:

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; 

请记住,这可能有多个行,如果温度在多个日期相同。没有简单明智的方式将如何将它加入到一个表中。

如果每天多次测量,并正在寻找在每一天的最高温度/湿度,那么你要使用GROUP BY功能。然后,您可以加入的时间戳的日期()函数的是这样的:

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()此功能是必要的,因为你可能有只有一个表可能有数据的日期。

此连接,如果你有大量的数据,在这种情况下,你可能想看看同组函数结果创建临时表,然后加入只是每日期单列效率不高。该柱的