Why can't you mix Aggregate values and Non-Aggregate values in a single SELECT?

后端 未结 6 1866
我寻月下人不归
我寻月下人不归 2020-11-29 07:04

I know that if you have one aggregate function in a SELECT statement, then all the other values in the statement must be either aggregate functions, or listed in a GROUP BY

6条回答
  •  有刺的猬
    2020-11-29 07:12

    Your query implicitly asks for different types of rows in your result set, and that is not allowed. All rows returned should be of the same type and have the same kind of columns.

    'SELECT name, surname' wants to returns a row for every row in the table.

    'SELECT COUNT(*)' wants to return a single row combining the results of all the rows in the table.

    I think you're correct that in this case the database could plausibly just do both queries and then copy the result of 'SELECT COUNT(*)' into every result. One reason for not doing this is that it would be a stealth performance hit: you'd effectively be doing an extra self-join without declaring it anywhere.

    Other answers have explained how to write a working version of this query, so I won't go into that.

提交回复
热议问题