简体   繁体   中英

Can non-grouped fields and fields with aggregate functions exists together?

As far as I understand if there are some fields which expression contains aggregate function, then just normal field in the same query are not accepted - each field should be either aggregate, either included in "group by" section. Is it so?

If I have a query text with some aggregate functions, and I have a script(in any language), which determines non-aggregate fields, will it be logically correct automatically include them to group section, if they are not there? Or there are some cases exist when it will not be correct?

Thanks

This is a little complicated. But the simple answer to your question is that yes, you should include all non-aggregated columns/expressions.

Two caveats follow. If you have expressions, be sure to include the expression , not the column. So don't do this:

select date(datetimecol), count(*)
from t
group by datetimecol;

The correct logic is:

select date(datetimecol), count(*)
from t
group by date(datetimecol);

The second caveat involves primary keys. If a_id is the primary key in a , then this is fine:

select a.*, count(*)
from a join
     b
     on <whatever>
group by a.a_id;

However, including all the columns in the group by is also correct.

Note: This is called functional dependence and is supported by standard SQL. However, MySQL is one of the few databases that actually implements this functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM