Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL using MAX() with WHERE clauses

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...

like image 611
Joshua Bambrick Avatar asked Apr 01 '12 17:04

Joshua Bambrick


People also ask

Can we use Max in WHERE clause in MySQL?

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.

Can we use Min and Max in WHERE clause?

We can't reference the result of an aggregate function (for example MAX() ) in a WHERE clause of the same SELECT .

Can we use MAX function in case statement?

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.

What is Max () in MySQL?

The MAX() function returns the maximum value in a set of values.


2 Answers

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;
like image 96
Andriy M Avatar answered Sep 22 '22 12:09

Andriy M


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')
like image 42
Klas Lindbäck Avatar answered Sep 19 '22 12:09

Klas Lindbäck