22

How can I use the distinct clause with Zend\Db\Sql\?

Chris Kempen
  • 9,491
  • 5
  • 40
  • 52
Emmanuel Gauthier
  • 531
  • 2
  • 4
  • 15
  • https://github.com/zendframework/zf2/blob/master/library/Zend/Db/Sql/Expression.php – Sam Mar 11 '13 at 20:43

4 Answers4

35

I found this very usefull solution on http://blog.abmeier.de/php/zf2-select-distinct

$sql = new Sql($adapter);
$select = $sql->select();
$select->quantifier('DISTINCT');
Mihai
  • 366
  • 3
  • 5
19

Use an expression in your column selection.

$select = new Select('tablename');
$select->columns(array(new Expression('DISTINCT(id) as id')));
Andrew
  • 12,617
  • 1
  • 34
  • 48
  • 7
    also $select->columns(array('id' => new Expression('DISTINCT(id)'))); Key will become alias – Greg Apr 18 '13 at 13:56
  • This is a hack, and wrong. "distinct" is a property of the row, not of the column. Once you want more than one column, this will not work at all. – bart Jul 13 '21 at 07:34
19

While Mihai Dobre's answer is correct, I think you should use the constants provided by the framework instead of using a string literal. This will make your code more future-proof.

$sql->select()->quantifier(\Zend\Db\Sql\Select::QUANTIFIER_DISTINCT)
Julian
  • 8,808
  • 8
  • 51
  • 90
0

This worked best for me.

$select = $this->select()
          ->distinct()
          ->where('user_id = ?', $user_id);

http://webphplearn.com/blog/blogdetail/Distinct_in_Zendframework2

Tristan Hudson
  • 151
  • 1
  • 12