mysql - 查询获取两个表mysql中的最大值

标签 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() 函数是必要的,因为您的日期可能只有一个表包含数据。

如果您有大量数据,则此联接效率不高,在这种情况下,您可能需要考虑使用组函数结果创建临时表,然后仅联接每个日期的单行。

关于mysql - 查询获取两个表mysql中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611571/

相关文章:

php - 将 SQL 查询转换为 Zend DB Select

mysql - 防止 mysql join View 中出现重复

php - 如何计算每行之间的时间差(+/-)?

mysql - 我需要使用 LENGTH 函数从 2 个不同的表中提取值,但仅使用 1 个查询

php - 如何检索多列的总和?代码点火器

PHP MySQL 最接近邮政编码

PHP表单与MYSQL仅发布我输入的内容。而不是搜索结果

php - WAMP 2.4 - MYSQL 实例图标保持橙色

Mysql 基于集合中值的存在性的情况

mysql - 尽管我的系统完全在 64 位上运行,为什么 64 位 mysql odbc 连接器不能与 VBA 很好地配合?