mySQL count多個表的資料例項詳解

2022-09-25 23:48:12 字數 2283 閱讀 9979

一、實現需求

最近在做成就係www.cppcns.com統,成就中有很多維度都和數量有關,比如使用者粉絲數達到多少50個,授予 名揚四海 稱號,使用者點讚達到 100 次,授予 點讚聖手 稱號等等。

粉絲數在user_relation表

點讚數在user_praise表

按照以往的做法,如果需要查詢使用者的這些資料,又因為資料是在不同的表中,所以往往會分開多條 sql 查詢,比如:

select count(*) mysh from user_relation where other_uid =123456;

select count(*) dzss from user_praise where praise_uid = 123456;

然後將查詢出的資料封裝在乙個物件中,返回給客戶端或者另做他用,如果需要統計的表少點還可以,但是像成就系統中,往往有各種各樣的成就,我們現在涉及到 12 張表,如果按照這種來查詢,那麼就要寫 12 條 sql 查詢 12 次,這讓人有點不爽。

二、能否用一條 sql 語句實現呢

答案是肯定的

像這種將多個表不同的資料,整合在乙個表中的時候,我們可以採用union操作。

首先將使用union改寫以上語句:

wrzm,mysh,sgbh from (

select count(*) wrzm,0 mysh,0 sgbh from user_witness where plan_uid = 123456

union all

select 0 wrzm,count(*) mysh,0 sgbh from user_relation where other_uid = 123456

union all

select 0 wrzm,0 mysh,count(*) sgbh from plan_stage where uid = 123456 and status = 1

) t;

按照上面查詢出來的結果為:

mysql_count_results

我們發現這個結果已經有點像樣了,如果能將表中wrzm,mysh,sgbh的資料三行變成一行,那就好了。於是我們很自然可以想到用sum(當然一開始我沒想到,經過朋友提醒),於是改寫上面的 sql :

select sum(wrzm) wrzm,sum(mysh) mysh,sum(sgbh) sgbh from (

select count(*) wrzm,0 mysh,0 sgbh from user_witness where plan_uid = 123456

union all

select 0 wrzm,count(*) mwww.cppcns.comysh,0 sgbh from user_relation where other_uid = 123456

union all

select 0 wrzm,0 mysh,count(*) sgbh from plan_stage where uid = 123456 and status = 1

) t;

然後得出的結果為:

mysql_count_result_2

至此,得到了我們想要的結果,在一條 sql 語句中實現了多個表的count統計。

三、拓展

如圖,我們能獲取到的僅僅是乙個使用者的資料,但是我們需要統計的是user_info中的所有使用者,那麼也很簡單,我們再次進行改寫:

select uid,sum(wrzm) wrzm,sum(mysh) mysh,sum(sgbh) sgbh from (

select plan_uid uid,count(*) wrzm,0 mysh,0 sgbh from user_witness

group by plan_uid

union all

seleukkkact other_uid uid,0 wrzm,count(*) mysh,0 sgbh from user_relation

group by other_uid

union all

select uid,0 wrzm,0 mysh,count(*) sgbh from plan_stage where status程式設計客棧 = 1

group by uid

) t group by uid;

查詢結果為:

mysql_count_results_3

在這個結果中,如果我們需要檢視具體某乙個使用者,那麼在最後加上

where uid = 123456即可,如果要排序的話,那麼直接加上order by即可。

總結本文標題: mysql count多個表的資料例項詳解

本文位址:

mysql count 空表為何會很慢

count 乙個 空表 為什麼會很慢呢?只有幾十行資料為什麼 select from table limit 1 需要300ms select min pk fromtable 也會慢?見下例 dba localhost test 18 14 32 show create table test hm...

MySQL COUNT語句的索引使用

我們先準備好測試資料 create table user test count id int primary keynot null auto increment name varchar 45 age int email varchar 60 birthday date engine innodb...

mysql count 幾種寫法時間的比較

mysql 資料庫有一張表,資料量是6800w條,現在使用count 對資料進行統計 1.首先看下mysql的表結構 create table business dict url id int 11 not null auto increment,company name varchar 100 d...