Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select row where id=max(id)

I have a table which holds product information with multiple instances of a product with the same title, identified by different colours and their ids. I need to output the entire row where the id = the maximum id grouped by the title, but I can't seem to get it to do this. Here is a very simplified table and some example data:

id   title   colour   description

1    rico    red      blah1
2    rico    blue     blah2
3    rico    yellow   blah3
4    katia   black    blah4
5    katia   white    blah5

In this example with my code, I get 1 rico red blah1 when I want 3 rico yellow blah3.

Here is the code I am using:

SELECT pd_id, pd_title, pd_description, pd_colour,
       pd_price,pd_large_image,pd_date,cat_sub_id_3,pd_new
FROM product 
WHERE 
  cat_sub_id_1 = '".$cat_sub_id."' 
  AND cat_parent_id='".$cat_parent_id."' 
GROUP BY pd_title 
HAVING MAX(pd_id) 
ORDER BY pd_id DESC

UPDATE: Thanks guys,

I used alinoz's answer to come up with the following code which works :)

SELECT
    pd_id,pd_title,pd_description,pd_colour,pd_price,pd_large_image,pd_date,cat_sub_id_3,pd_new
FROM product 
HERE cat_sub_id_1 = '".$cat_sub_id."' AND cat_parent_id='".$cat_parent_id."'
AND pd_id IN (
    SELECT max(pd_id)
    FROM product
    WHERE cat_sub_id_1 = '".$cat_sub_id."' AND cat_parent_id='".$cat_parent_id."'
    GROUP BY pd_title
    )
GROUP BY pd_title
ORDER BY pd_id DESC
like image 480
user1001369 Avatar asked Oct 18 '11 15:10

user1001369


People also ask

How can I select the row with the highest ID in SQL?

SQL MIN() and MAX() Functions The MAX() function returns the largest value of the selected column.

Can we use Max in WHERE clause?

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 .

How do I select 3 max values in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.


2 Answers

Aaahhh, the good old greatest-n-per-group...

select *
from YourTable yt
inner join(
    select title, max(id) id
    from YourTable
    group by title
) ss on yt.id = ss.id and yt.title = ss.title

Of course, you should adapt this to your needs accordingly.

Also, I think this is a "must read": SQL Select only rows with Max Value on a Column

like image 195
Adriano Carneiro Avatar answered Sep 22 '22 13:09

Adriano Carneiro


I think this might work (not tested):

SELECT * FROM that_table WHERE id IN (
SELECT MAX(id) FROM that_table GROUP BY title
) /* AND this = that */
like image 22
Salman A Avatar answered Sep 23 '22 13:09

Salman A