Mysql中g(shù)roup by的問題。。
問題描述
Mysql中,下面這樣的寫法是可以允許的。但是嚴不嚴謹,支不支持這樣寫?有疑惑過不去這個坎,請大家?guī)兔纯础?/p>
select * from user group by user_name;
問題解答
回答1:最詳細的文檔說明在官網(wǎng)找到了。
MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)
來源:https://dev.mysql.com/doc/ref...
回答2:select中的字段需要在group by中強制寫出來select user_name from user group by user_name;
http://blog.csdn.net/u2830560...
回答3:首先理解下分組是個什么概念,分組后可以達到什么樣的效果;分組是為了按組這個屬性進行統(tǒng)計分析;例如一個學生表中,按性別分組,可以統(tǒng)計出男生多少人,女生多少人。在查詢結(jié)果列中,必然是sum,count等聚合函數(shù)組成。例如:select count(*),sex from student group by sex;如果是select * from user group by user_name;是想要得到一個什么樣的統(tǒng)計結(jié)果呢?mysql5.6默認可以使用這種寫法select * from user group by user_name,但實際上在內(nèi)部對語句做過轉(zhuǎn)換;mysql5.7以后默認不能使用此中寫法,會報錯。所以寫之前先想想我需要通過分組統(tǒng)計什么內(nèi)容,使用適合的聚合函數(shù)
回答4:在SQL語句中使用GROUP BY要注意三點1:不能使用別名;2:除了函數(shù)字段,select中出現(xiàn)的字段都必須出現(xiàn)在group by中,3:別名不能使用保留字這三點MYSQL都是沒有要求的!我們再來看你這個語句,如果user表只有一個字段user_name ,那么這個語句沒有問題,如果user表有超過一個字段,那么這個語句在mysql是沒有問題的,但是在oracle和sqlserver是有問題的
回答5:select * from user group by user_name;//這么寫其實也沒問題 但是 實際上 你使用 group by 的時候 你需要用的 就只有 user_name 這個字段吧(通常來說)//用什么字段就取什么字段就好。不一定要用 ‘*’ 用誰取誰就好回答6:
如果存在user_name這個字段,那么就沒有問題。group by是按字段分組,通常和聚合函數(shù)一起使用,像你這個sql也是可以執(zhí)行的。只不過user_name通常都是唯一的,按唯一字段去分組是沒有意義的。
回答7:這個屬于mysql的特殊功能支持,如@xuexiphpa所說,可以通過參數(shù)關(guān)掉。
但不建議使用,group by分組后,理論上返回的記錄數(shù)比分組前少了,一般會通過聚合函數(shù)來返回一些統(tǒng)計數(shù)據(jù)。直接使用select *,就不確認返回的是那一條記錄了。
回答8:一般個聚合函數(shù)結(jié)合用的比較多
回答9:group by聚合分組后,select子句中的元素最好只保持:1、常數(shù)2、group by指定的列名3、聚合函數(shù),如count()、avg()、sum(*)等等
你這樣*的結(jié)果,只列出了每一個分組的一條記錄,而且不知道是第一個還是是隨機的一個值
相關(guān)文章:
