關於mysql的初步學習 (四)

來源:互聯網
上載者:User

標籤:group   作用   sel   article   包含   運算   注意   sql   under   

 繼續深入學習下 group by的使用:

  它的文法是

    select

            column_name1,column_name2,。。。,function(column_name)

     from

            table_name

     where

            column_name operator valuue

    group by

           column_name1,column_name2,。。。

   

   比如說:求一個班上的男女各多少人,並且有哪些人,上面的就都用得著:

    select 性別,group_concat(人名),count(人名) from 表 group by sex;

    如所示一樣:

     select count(*),CarTypeID,group_concat(LicencePlate)from carinfotb_common  group by CarTypeID;

                   

     我是這麼想的:

  1、Group by按照某一個column_name分組 ,那麼 查詢的列就肯定會包含這個column_name,function函數可以是某一個column_name 也可以是 “*”。但是要注意區別:

                                  count(*)對行的數目進行計算,包含NULL
                                  count(column)對特定的列的值具有的行數進行計算,不包含NULL值。
                                  count()還有一種使用方式,count(1)這個用法和count(*)的結果是一樣的。

   2、 函數可以包含 count,sum,avg等這些數值運算。

                                     

   3、也可使用group_concat(column_name,。。。)函數,他可以把你分組裡面所查的column_name值以‘,’串連起來,得到一個字串。

   4、也可以使用order by 進行排序。

select count(*),CarTypeID,group_concat(LicencePlate)from carinfotb_common group by CarTypeID ORDER BY COUNT(*) DESC;

       

   5、也可以使用 where 和having查詢篩選資料

                  select count(*),CarTypeID,group_concat(LicencePlate)from carinfotb_common WHERE CarTypeID !=‘‘ group by CarTypeID ORDER BY COUNT(*) DESC;

  • where 子句的作用是在對查詢結果進行分組前,將不符合where條件的行去掉,即在分組之前過濾資料,where條件中不能包含聚組函數,使用where條件過濾出特定的行。
  • having 子句的作用是篩選滿足條件的組,即在分組之後過濾資料,條件中經常包含聚組函數,使用having 條件過濾出特定的組,也可以使用多個分組標準進行分組。

               select count(*),CarTypeID,group_concat(LicencePlate)from carinfotb_common WHERE CarTypeID !=‘‘ group by CarTypeID having count(*) > 10 ORDER BY COUNT(*) DESC;

   6、group by 可以是多個column_name 。那分組的條件是多個column_name之間的彼此聯絡。

 

 關鍵是搞起需求的意圖,弄清楚分組的列,運用好函數。  參考文章:http://blog.csdn.net/xxpyeippx/article/details/8059910寫的更詳細。運用了多個列分組。 

詳細的資料查詢結果不是很清晰

 

關於mysql的初步學習 (四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.