I created a custom module with a database table with the help of this article.

I have a program which syncs stock from my physical store to online store. Every time I sync the stock, I add the sku,name, sync data and time, also the qty to the custom database table. There can be multiple entries for the same sku in the table as the same product can be synced multiple times.

Initially I was taking a report of the unique entries from the database table using this, where I was only getting the skus.

$collections = Mage::getResourceModel('module/namespace_collection')->distinct(true)->addFieldToSelect('sku')->load();
foreach( $collections as $collection){
    //add to csv

Now I want to get the sku and qty of the unique entries with the latest sync data and time for that particular sku. To get this I tried to use

$collections = Mage::getResourceModel('module/namespace_collection')->distinct(true)->addFieldToSelect('sku')->addFieldToSelect('qty')->addFieldToSelect('date')->load();

but I am getting all the entries in the custom table. Can some one help me out with this?


I found an SQL select to do this

SELECT t.sku,t.date,t.store_name
FROM my_database_table t
    SELECT sku, max(date) as MaxDate
    FROM my_database_table
    GROUP BY sku
) tm on t.sku = tm.sku and t.date = tm.MaxDate;

How do I convert this into a getCollection statement?

1 Answer 1


In this case,you need to create custom mysql code which will create mysql like this

Call your collection:

$collections = Mage::getResourceModel('module/namespace_collection');

Call the db resource singleton model

 $resource = Mage::getSingleton('core/resource');

Carry connection write connection

$writeConnection = $resource->getConnection('core_write');

Make a custom collection by calling write connection and make a custom subquery:

$subSelect =$writeConnection->select()
                array(' table2' => $collections->getTable('module/namespace')),
                array( 'sku', 'MaxDate'=>new Zend_Db_Expr("max(date)"))

Join table

                array(' tm' => new Zend_Db_Expr(sprintf('(%s)',$subSelect->assemble()))),
                'main_table.sku = tm.sku and main_table.date = tm.MaxDate,

Select your selective columns


Code is not tested and put basic of concept

  • Thanks Amit. Sorry for the late response. I ended up using the direct sql query.
    – James
    Commented May 5, 2015 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.