Search code examples
phpmysqlzend-frameworkzend-db

Explain this Zend_Select and Convert to SQL Query?


$select->from(array('u'=>'user'),array('count'=>'distinct count(*)'))
                   ->joinLeft(
                        array('d' => 'details'),
                        'u.detailsid = d.detailsid',
                        array());

I have:

SELECT * FROM user
LEFT JOIN details ON
details.detailsid = user.detailsid;

But where does the count fit it?


Solution

  • It's the columns.

    SELECT DISTINCT count(*) AS count FROM user AS u
    LEFT JOIN details AS d ON
    d.detailsid = u.detailsid;
    

    See http://framework.zend.com/manual/1.12/en/zend.db.select.html

    In the second argument of the from() method, you can specify the columns to select from the respective table. If you specify no columns, the default is "*", the SQL wildcard for "all columns" […] You can list the columns in a simple array of strings, or as an associative mapping of column alias to column name. If you only have one column to query, and you don't need to specify a column alias, you can list it as a plain string instead of an array.

    On a side note, you can simply echo the query to see what it would produce (same page as above):

    Converting a Select Object to a SQL String - If you need access to a string representation of the SQL query corresponding to the Zend_Db_Select object, use the __toString() method.