1. 程式人生 > >mysql統計查詢

mysql統計查詢

好久沒寫部落格了,不知道寫撒,就寫寫統計吧

很多時候我們都會用到統計查詢,在現在一個後臺沒有點什麼折線圖,什麼圖示展示都會顯得這個後臺一點不高大上,

列舉一下表

drop table if exists oa_users;

/*==============================================================*/
/* Table: oa_users                                              */
/*==============================================================*/
create table oa_users
(
   u_id                 int not null auto_increment,
   u_type               char(2) default '1' comment '1:普通使用者 2:會員使用者3:超級vip使用者 ',
   c_id                 int,
   u_name               varchar(32),
   u_addresscode        char(12),
   u_status             char(4),
   u_disable            char(2),
   u_password           varchar(64),
   u_uniond             varchar(64) binary,
   u_db                 bigint,
   primary key (u_id)
);
drop table if exists oa_chinnel;

/*==============================================================*/
/* Table: oa_chinnel                                            */
/*==============================================================*/
create table oa_chinnel
(
   c_id                 int not null auto_increment,
   c_name               varchar(32),
   c_remark             varchar(256),
   primary key (c_id)
);

下面來1,巧用group by

就那上面的表來說吧,例如使用者型別有三種。

查詢三種不同型別的使用者

SELECT case when u_type=1 then 1 WHEN u_type = 2 THEN 2 else 3 end as names,COUNT(1) as countnumber FROM `oa_users` GROUP BY case when u_type=1 then 1 WHEN u_type = 2 THEN 2 else 3 end
這樣就會獲取資料庫裡面所有u_type三種類型的資料

上面的情況是知道型別的情況下面可以這麼做,如果不知道型別呢

例如獲取不同渠道使用者的統計數量

select count(1) as countnumber from oa_users group by c_id
很簡單,還有例如查詢一年12個月的註冊量,對上面oa_users表增加一個欄位createtime   就可以了也可以用case when 

還可以用臨時表,其實很多時候查詢用臨時表,時間會節約不少,還有一對多用inner join  

select t.myYear as 年份,t.monthNo as 月份,count(1) as 數量統計  from(select month(createtime) as monthNo, year(createtime) as myYear, u_id from oa_users) as t  where t.myYear='2016'  group by t.monthNo  
還有做出微博一樣的熱點中國地圖,結合百度或者高德poi來做,文章裡面有一個搶購的專案裡面有百度poi地址,可以借鑑一下,為了公德,請使用自己的key,最近key請求飽滿了,獲取到使用者區域code(adress_code)去地址表裡面獲取省市區,因為這是我的部落格使用者表,做了分表設計,所以這裡看不出來,獲取到的poi地址取第一個就是一個點了