I am having some issues creating a mySQL query with PHP. 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.
$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. The previous observation has the highest Record_Time (a Unix datestamp), so it's unclear to me why this would not work...
The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.
We can't reference the result of an aggregate function (for example MAX() ) in a WHERE clause of the same SELECT .
The SQL MAX function can also be used with the GROUP BY statement. Let me show you a use case to make you understand its uses. The GROUP BY statement groups rows that have the same values from the specified column and return the result.
The MAX() function returns the maximum value in a set of values.
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:
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'.
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:
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With