views:

88

answers:

1

Whenever I do a:

$this->Job->find('all', array(
        'group' => array('Job.some_field'),
        'recursive' => -1
    ));

I get a :

SQL Error: Column 'jobs.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

With MySQL it works fine but with SQL Server 2008 it seems that group by doesn't work anymore. How do I fix this? Thanks in advance SQL gurus

+1  A: 

The query is translated into something like this:

SELECT  *
FROM    Job
GROUP BY
        some_field

This is not a valid query according to SQL standards, however, it works in MySQL because of MySQL's GROUP BY extensions.

You need to leave only grouped columns or aggregates in the SELECT clause:

SELECT  some_field, COUNT(*)
FROM    Job
GROUP BY
        some_field

with something like this:

$this->Job->find('all', array(
        'fields' => array('Job.some_field', 'COUNT(*)'),
        'group' => array('Job.some_field'),
        'recursive' => -1
    ));
Quassnoi
What if I'm using containable and have joins in my query?
bakerjr
@bakerjr: you need to make you query so that it translates into a valid `SQL`, that is no ungrouped *and* unaggregated columns in the `SELECT` clause.
Quassnoi
Got it thanks Quassnoi. Although what I really want is to get the distinct values of a field along with the joins that's why I'm using group in my find (plus containable).You answered the question on this post though :)
bakerjr
@bakerjr: if you need `DISTINCT` values, you will most probably benefit from rewriting the joins as the `IN` conditions.
Quassnoi
I guess I'm forced to write it as custom query in cake, do you agree? :/
bakerjr