5

I want to use distinct in magento.

SELECT DISTINCT level FROM `student`

I am trying this code

 $collection = Mage::getModel('school/student')->getCollection()
      ->distinct(true)
      ->addAttributeToSelect('level');

But its not working.

So how to use distinct in magento

2 Answers 2

20

Use group by instead of distinct.

Add $collection->getSelect()->group('level').

Use group by instead of ->distinct(true).

Code:

$collection = Mage::getModel('school/student')->getCollection()
          ->addFieldToSelect('level');

$collection->getSelect()->group('level')

Or use:

$collection = Mage::getModel('school/student')->getCollection()->getSelect()
      ->columns('level')
      ->group('level');
5
  • addAttributeToSelect is not working
    – ND17
    Commented Jun 4, 2015 at 11:13
  • as it non eav collection so addAttributeToSelect not work ,use addFieldToSelect
    – Amit Bera
    Commented Jun 4, 2015 at 11:14
  • I m not getting value of level field
    – ND17
    Commented Jun 4, 2015 at 11:24
  • please show table structure of this model
    – Amit Bera
    Commented Jun 4, 2015 at 11:28
  • Its not working bcz of my silly mistake.Its working now
    – ND17
    Commented Jun 4, 2015 at 11:39
3

Tested on Magento ver 1.9.4.3.

$collection = Mage::getResourceModel('sales/order_collection')
    ->addFieldToSelect('customer_id')
    ->distinct(true)
    ->addFieldToFilter('entity_id', ['gteq' => 200737]);

The resulting MySQL statement is:

SELECT DISTINCT `main_table`.`customer_id` 
FROM `sales_flat_order` AS `main_table` 
WHERE (main_table.entity_id >= 200737)

To return a one-dimension array of customer_id, do:

$result = $collection->getColumnValues('customer_id');

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.