我以前也看到过类似的问题,但它们似乎都是在讨论如何获得最小值或最大值。我需要两者都得到,最好是一个查询。我无法理解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-14min应8.69且max应14.14
对于2018-05-15min应8.77且max应13.42
如何从tempúux列中获取实际的最小值和最大值?驱动正确查询的逻辑是什么?

最佳答案

您似乎正在将数值存储为字符串。你真的应该修正数据。但是,您可以修复查询。在我看来,最简单的方法是隐式转换:

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;

注意pressurecondition不在您的GROUP BY中,因此值是从任意行中选择的。这是一个非常糟糕的做法,这意味着您的查询在几乎任何其他数据库中都无法工作。
您可以通过执行以下操作来修复数据:
alter table infoboard.forecasts
    modify column temp_min decimal(6, 3),
    modify column temp_max decimal(6, 3);

我想你也会想为pressure做同样的事情。

10-01 23:50
查看更多