简体   繁体   English

PHP,MySQL。 最低和最高价值的日,月和年

[英]PHP, MySQL. Min and max value day, month and year

Edit for clarification: 编辑以澄清:

This is my table: 这是我的桌子:

ID      Datetime            Date        Temp
6043    2016-05-24 10:20:00 2016-05-24  19.3
6042    2016-05-24 10:15:00 2016-05-24  19.1
6041    2016-05-24 10:10:00 2016-05-24  19.1
6040    2016-05-24 10:05:00 2016-05-24  19.1

What I'm trying to do is to select the row with the highest "Temp". 我想做的是选择具有最高“温度”的行。

This is my query: 这是我的查询:

SELECT max(temp) as maxtemp FROM weatherdata WHERE day(date) = 24

The query only gives me the maxtemp, how can I get the ID and Datetime? 该查询仅给我最大温度,如何获取ID和日期时间?

Goal is to get the max-value for each day in my table (WHERE day(date) = xx) 目标是获取表格中每一天的最大值(WHERE day(date)= xx)

Kind Regards 亲切的问候

It looks to me like you are trying to get your entire weatherdata observation row for the observation that contains the highest temperature in any given month. 在我看来,您正在尝试获取包含任何给定月份最高温度的观测的整个weatherdata观测行。

This takes two steps, as you have realized. 您已经意识到,这需要两个步骤。 The first step: find the highest temperature observation in each month. 第一步:找到每个月最高的温度观测值。 You do that like so: 您可以这样操作:

              SELECT MAX(temp) temp, LAST_DAY(`datetime`) month_ending
                FROM weatherdata
               GROUP BY LAST_DAY(`datetime`)

The trick here is to use LAST_DAY() to figure out in which month each observation occurs. 这里的技巧是使用LAST_DAY()来确定每个观察发生在哪个月。 It takes any date, datetime, or timestamp item and figures out the date of the last day of its month. 它采用任何日期,日期时间或时间戳项,并计算出该月最后一天的日期。 This query gives you a result set containing one temp per month, for the highest temp in the month. 该查询为您提供了一个结果集,该结果集每月包含一个临时表,该月中的最高临时表。 Try it. 试试吧。 Make sure it works for you. 确保它适合您。

Next, you should join that to your detailed observation table, like so: 接下来,应将其加入到详细的观察表中,如下所示:

 SELECT w.*
   FROM weatherdata w
   JOIN (
              SELECT MAX(temp) temp, LAST_DAY(`datetime`) month_ending
                FROM weatherdata
               GROUP BY LAST_DAY(`datetime`)
        ) m   ON w.temp = m.temp
             AND LAST_DAY(w.`datetime`) = m.month_ending
  ORDER BY w.`datetime`

This will give you the detailed observations. 这将为您提供详细的观察。 Notice that if the highest temperature occurred on more than one observation in any given month, you'll get them all. 请注意,如果在任何给定的月份中有多个观测值都出现了最高温度,您将全部获得。

Finally, if you only want some months, put this WHERE clause right before the ORDER BY clause 最后,如果只需要几个月的时间,请将此WHERE子句放在ORDER BY子句之前

   WHERE `datetime` >= '2016-04-01 
     AND `datetime` <  '2016-05-01  -- to get April 2016 

Pro tip: don't use names of datatypes, like datetime , as column names. 专家提示:不要将数据类型的名称(如datetime )用作列名。 It makes it hard to troubeshoot your database. 这使得很难对数据库进行故障排除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM