You can do
select max(id), address, max(date) as latest from searches group by address order by latest desc
According to sqlfiddle , which does exactly what I think you want.
This is not exactly the same as the output of your request, which does not seem to care about which identifier is returned. However, the request must specify something that is done here using the aggregate function "max".
I don't think you're lucky with the auto-generated ActiveRecord query methods for this case. So just add your own query method using this SQL for your model class. This is completely standard SQL, which will also work mainly with any other DBMS.
Edit:. The big weakness of the query is that it does not necessarily return the actual records. If the highest identifier for a given address does not match the highest date for this address, the resulting "record" will be different from the one actually stored in the database. Depending on the use case, which may or may not matter. For Mysql, just changing max(id) to id will fix this problem, but Oracle IIRC has a problem with this.
source share