Domanda

I'm having difficulty in creating a select query using an inner join the Zend Framework way.

I have looked at the manual and can't work out how to write the following statement:

SELECT m.user_id, m.timestamp, m.status
FROM (
     SELECT user_id, max( timestamp ) AS timestamp
     FROM timeclock_clockings
     GROUP BY user_id
     ) AS x
INNER JOIN timeclock_clockings AS m ON m.timestamp = x.timestamp

Any help would be appreciated.

Thanks

È stato utile?

Soluzione

You can accomplish this using Zend_Db_Expr() and creating two $select instances.

$db = new Model_TimeclockClockings(); // or whatever yours is named

$nested = $db->select()
    ->from('timeclock_clockings', array('user_id', 'max(timestamp) AS timestamp'))
    ->group('user_id');

$select = $db->select()
    ->setIntegrityCheck(false) // required for joins
    ->from(array('x' => new Zend_Db_Expr('(' . (string) $nested . ')')))
    ->join(array('m' => 'timeclock_clockings'), 'm.timestamp = x.timestamp', array());

echo $select; // this should look like your query

That's about it. There are actually several other similar questions like this on SO. But I figured perhaps you were having trouble making sense of it.

Note that join() is an INNER JOIN, you can also use joinLeft() for LEFT JOIN. Or joinRight() etc etc.

More info on joins here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top