tags:

views:

78

answers:

5

This is my example of my table:

id | name | foreign_id |

1 a 100

2 b 100

3 c 100

4 d 101

5 a 102

6 b 102

7 c 102

I would like to get the distinct file with the latest foreign_id (bigger number but not necessarily biggest). In this example, it would be row with id 4,5,6,7. Anyone has any idea? Thank you very much!

A: 

SELECT * FROM table_name WHERE foreign_id > 100

geff_chang
geff, I edited my question to clarify it a bit.
Patrick
@Patrick: Does the updated query answer your question now?
geff_chang
+1  A: 

Could you try something like below :-

SELECT Id,Table1.Name,Table1.Fid FROM Table1 INNER JOIN 
(SELECT Name,Max(FId) AS FId FROM Table1 Group By Name)
Table2 ON Table1.FId=Table2.FId AND Table1.Name=table2.Name

This works in Sql Server atleast. Please check in MySQL. Sorry, I dont have MySQL to test this.

ydobonmai
tested and work perfect!
Patrick
A: 

You could do something like:

select *
from table_name
where max_id_you_want = (select max(id_you_want) from table_name)
John
This list 5,6 and 7 and does not list 4 as asked in the question.
ydobonmai
yes, but it is a way to the solution. I assume that the most recent id will be the greatest or you would need to find another way to get it. to get the set of all of the ids that are the greatest you could do something like select whatever from some_table where id_you_want is in (query returning the result you are looking for)
John
+1  A: 

Sounds like you just want this:

SELECT name, MAX(foreign_id)
FROM table
GROUP BY name;

If you need the ID (I'm guessing you won't, since name and foreign_id should probably be unique, making the ID column unnecessary), I think MySQL will allow you to get that by just adding that column to the SELECT list - although this is non-standard SQL. If you want standard SQL, then you want something like Ashish wrote.

Michael Madsen
A: 
SELECT * FROM table
GROUP BY name
having MAX(foreign_id);
Manuel Darveau