22

I'm trying to use the MAX function of MySQL to retrieve the latest dates from my table.

$_updates = Mage::getModel('ticket/updates')->getCollection();  
$_updates->getSelect()->columns('MAX(created) as max_created')->group(array('status_id'));

This is the resulting query:

SELECT `main_table`.*, MAX(created) AS `max_created` FROM `em_ticket_updates` AS `main_table` GROUP BY `status_id` 

The problem with this is that if all the fields are included (main_table.*) it does not function correctly.

Is there a way to remove main_table.* from the query and only use specific fields?

Thanks.

Jjj
  • 762
  • 3
  • 8
  • 18

4 Answers4

48

A Zend trick can be used here.

$_updates->getSelect()
    ->reset(Zend_Db_Select::COLUMNS)
    ->columns('MAX(created) as max_created')
    ->group(array('status_id'));

NOTE:

For EAV collection you must re-add the entity_id or you will have an error when the collection is loaded.

    $collection = Mage::getModel('catalog/product')
        ->getCollection();
    $collection->getSelect()
        ->reset(Zend_Db_Select::COLUMNS)
        ->columns(array('entity_id')); 

    $collection
        ->addAttributeToSelect(array('image','small_image','thumbnail'))
        ->addFieldToFilter('entity_id', array('in' => $simple_ids));
clockworkgeek
  • 37,650
  • 9
  • 89
  • 127
  • Thank you! Saw the reset method on the Magento documentation but not the parameter value. Guess I should really study Zend too. – Jjj Dec 09 '11 at 01:16
  • Exactly what I was looking for since long. Absolutely awesome answer! Thanks for saving my day! – Prashant Oct 12 '12 at 14:59
  • Saved me from searching for too long, i ran into this issue when trying to set the columns in the "from" while adding "join" later and was scratching my head why it's including other columns from the joined tables. This reset trick solved it! – Long M K Nguyễn Mar 17 '20 at 18:47
7

Magento provide addFieldToSelect() fumctionality. Use below code to get specific field.

$Collection = Mage::getModel('showdown/votes')->getCollection();
$Collection->addFieldToSelect('id');
Neeraj Garg
  • 695
  • 3
  • 17
  • 38
5

I recognise this is an old post but I thought I'd post an alternative solution.

I had a similar problem myself, I eventually searched through the source until I reached Zend_Db_Select After consulting the Zend Documentation (Example 8).

$select = $db->select()
    ->from(array('p' => 'products'),
           array('product_id', 'product_name'));
Ash
  • 3,242
  • 2
  • 23
  • 35
0

Just need to use "getColumnValues"

$_updates = Mage::getModel('ticket/updates')->getCollection(); 
$columnValues = $_updates->getColumnValues('Your Column Name');
Rakesh
  • 756
  • 8
  • 10