Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting latest rows per distinct foreign key value

excuse the title, i couldn't come up with something short and to the point...

I've got a table 'updates' with the three columns, text, typeid, created - text is a text field, typeid is a foreign key from a 'type' table and created is a timestamp. A user is entering an update and select the 'type' it corresponds too.

There's a corresponding 'type' table with columns 'id' and 'name'.

I'm trying to end up with a result set with as many rows as is in the 'type' table and the latest value from updates.text for the particular row in types. So if i've got 3 types, 3 rows would be returned, one row for each type and the most recent updates.text value for the type in question.

Any ideas?

thanks,

John.

like image 356
John Beynon Avatar asked Jan 18 '10 17:01

John Beynon


People also ask

How do I SELECT the last 5 rows in SQL?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

Does DISTINCT work on multiple columns?

The DISTINCT clause can be applied to one or more columns in the select list of the SELECT statement.

What is the difference between SELECT * and SELECT 1?

Select * from any table will fetch and display all the column in that table, while Select 1 from any table will display one row with 1 without any column name.

Can I use distinct in middle of SELECT statement?

The DISTINCT clause filters out FULL DUPLICATE ROWS. It goes right after the SELECT keyword, since it applies to the entire row, not single columns. You cannot use it in between columns.


1 Answers

select u.text, u.typeid, u.created, t.name
from  (
    select typeid, max(created) as MaxCreated
    from updates
    group by typeid
) mu
inner join updates u on mu.typeid = u.typeid and mu.MaxCreated = u.Created
left outer join type t on u.typeid = t.typeid
like image 147
D'Arcy Rittich Avatar answered Oct 20 '22 11:10

D'Arcy Rittich