craphunter
craphunter

Reputation: 830

orderBy & groupBy query

My db entries

id | shop_id | last_changed
1  |     1   |   7 pm
2  |     1   |   8 pm
3  |     2   |   9 pm
4  |     2   |   8 pm
5  |     3   |   5 pm

My query should be that I only get entries with the id:

2, 3, 5 

When I do this:

$q = Doctrine_Query::create()
         ->from('list e')
         ->groupBy('e.shopname_id')
         ->orderBy('e.last_changed DESC')
         ->limit(6)
         ->fetchArray();

I get: 1, 4, 5. Even if I do e.last_changed ASC, it doesn't work.

I want only the entries those who have last_changed and different shop_id's. How can I do it?

Thanks!

Upvotes: 0

Views: 73

Answers (1)

Ross Smith II
Ross Smith II

Reputation: 12189

Try this:

$q = Doctrine_Query::create()
        ->select('e.shopname_id, MAX(e.id) AS id, MAX(e.last_changed) AS last_changed')
        ->from('list e')
        ->groupBy('e.shopname_id')
        ->orderBy('MAX(e.last_changed) DESC')
        ->limit(6)
        ->fetchArray();

Upvotes: 2

Related Questions