简体   繁体   English

MySQL使用MAX()和WHERE子句

[英]MySQL using MAX() with WHERE clauses

I am having some issues creating a mySQL query with PHP. 我在使用PHP创建mySQL查询时遇到了一些问题。 We have one table, called data_instant, with a series of cumulative observations being entered, called Count_Qty, and we want to extract the previous one to deduct from the new observation to calculate the increase. 我们有一个名为data_instant的表,其中输入了一系列累积观察结果,称为Count_Qty,我们想要提取前一个表以从新观察中扣除以计算增加。

$result = mysql_query("SELECT *, 
MAX(Record_Time) 
FROM data_instant 
WHERE Node_ID='$nodeID' AND Type='$type';

$row = mysql_fetch_array ($result);

Basically I'd expect the max Record_Time row to be returned, but instead it's just the first instance that's received. 基本上我希望返回最大的Record_Time行,但它只是收到的第一个实例。 The previous observation has the highest Record_Time (a Unix datestamp), so it's unclear to me why this would not work... 之前的观察具有最高的Record_Time(Unix日期戳),所以我不清楚为什么这不起作用......

If you want to get the row with the latest Record_Time value, just sort the rows in the descending order of Record_Time and get the top row: 如果要获取具有最新Record_Time值的行,只需按Record_Time的降序对行进行排序并获取最上一行:

SELECT *
FROM data_instant
WHERE Node_ID='$nodeID'
  AND Type='$type'
ORDER BY Record_Time DESC
LIMIT 1;

The where clause selects all rows matching Node_ID='$nodeID' AND Type='$type'. where子句选择与Node_ID ='$ nodeID'和Type ='$ type'匹配的所有行。

For each of those rows it will return all fields and the maximum record time. 对于每个行,它将返回所有字段和最大记录时间。

If you want the row with the maximum record time you need to add that to your where clause: 如果您希望行具有最长记录时间,则需要将其添加到where子句:

SELECT * 
FROM data_instant 
WHERE Node_ID='$nodeID' AND Type='$type' 
and Record_Time = (select MAX(Record_Time) 
        FROM data_instant 
        WHERE Node_ID='$nodeID' 
        AND Type='$type')

If you have more than the MAX being returned you should add the GROUP BY to your statement to ensure the correct aggregation: 如果返回的MAX超过MAX,则应将GROUP BY添加到语句中以确保正确聚合:

SELECT columnA,
    columnB, 
    MAX(Record_Time) 
FROM data_instant 
WHERE Node_ID='$nodeID' AND Type='$type'
GROUP BY columnA, columnB;

I'd expect the max Record_Time row to be returned 我希望返回最大的Record_Time行

Then you should just ask for that column: 然后你应该问这个专栏:

SELECT MAX(Record_Time) FROM data_instant 
WHERE Node_ID='$nodeID' AND Type='$type'

This will return the max record_time for the specified node_id and type. 这将返回指定node_id和type的max record_time。

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

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