我之前见过类似的问题,但他们似乎都在谈论只获得Min 或 Max值。我需要得到两者,理想情况下只需一个查询。我无法理解MySQL在MySQL中的工作原理 示例数据
+--------+--------+---------+---------+----------+
|temp_min|temp_max|pressure |condition|dt_txt |
+--------+--------+---------+---------+----------+
|9.27 |9.27 |1021.98 |Rain |2018-05-15|
|8.77 |8.77 |1021.22 |Rain |2018-05-15|
|9.99 |9.99 |1021.31 |Clear |2018-05-15|
|13.86 |13.86 |1021.41 |Clouds |2018-05-15|
|12.39 |12.39 |1019.71 |Rain |2018-05-14|
|13.42 |13.42 |1020.24 |Rain |2018-05-14|
|14.14 |14.14 |1020.41 |Rain |2018-05-14|
|9.01 |9.01 |1018.12 |Rain |2018-05-14|
|13.94 |13.94 |1020.73 |Rain |2018-05-14|
|5.64 |5.64 |1018.42 |Clouds |2018-05-14|
|10.65 |10.65 |1021.8 |Clouds |2018-05-14|
|8.69 |8.69 |1018.91 |Clouds |2018-05-14|
|... |... |... |... |... |
+--------+--------+---------+---------+----------+
逻辑和常识会决定这样的事情:
SELECT
MIN(`temp_min`) AS `temp_min`,
MAX(`temp_max`) AS `temp_max`,
`dt_txt`,
DAYNAME(`dt_txt`) AS `dayname`,
`pressure`,
`condition`,
`dt_txt`
FROM
infoboard.forecasts
WHERE `dt_txt` >= CURDATE()
GROUP BY `dt_txt`
ORDER BY `dt_txt` ASC;
结果是:
+--------+--------+---------+---------+----------+--------+
|temp_min|temp_max|pressure |condition|dt_txt | |
+--------+--------+---------+---------+----------+--------+
|10.65 |9.01 |1018.12 |Rain |2018-05-14|Monday |
|13.86 |9.99 |1021.98 |Rain |2018-05-15|Tuesday |
+--------+--------+---------+---------+----------+--------+
2018-05-14
分钟应为8.69
,最大值应为14.14
2018-05-15
分钟应为8.77
,最大值应为13.42
如何从temp_ *列获取真实的最小值和最大值以及驱动正确查询的逻辑是什么?
答案 0 :(得分:1)
您似乎将数字值存储为字符串。你真的应该修复数据。但是,您可以修复查询。在我看来,最简单的方法是隐式转换:
SELECT MIN(`temp_min` + 0) AS `temp_min`,
MAX(`temp_max` + 0) AS `temp_max`,
`dt_txt`, DAYNAME(`dt_txt`) AS `dayname`,
`pressure`, `condition`, `dt_txt`
FROM infoboard.forecasts
WHERE `dt_txt` >= CURDATE()
GROUP BY `dt_txt`
ORDER BY `dt_txt` ASC;
请注意,pressure
和condition
不在GROUP BY
中,因此从任意行中选择值。这是一个非常糟糕的做法,意味着您的查询几乎不能在任何其他数据库中使用。
您可以通过执行以下操作来修复数据:
alter table infoboard.forecasts
modify column temp_min decimal(6, 3),
modify column temp_max decimal(6, 3);
我怀疑你也想为pressure
做同样的事情。