2012-04-02 71 views
9

我有第一個表中顯示的表結構。如何在MySQL中進行優化?

並希望在單個查詢中獲取男性和女性的計數,以便請求只能在服務器上執行一次。

How to optimize this in MySQL ?

+0

請注意我知道如何獲取所有數據。但我想通過優化來實現 – Thompson 2012-04-02 16:13:00

+1

+1謝謝您清楚地顯示輸入和所需的輸出。 – pilcrow 2012-04-02 16:25:19

+0

@pilcrow:謝謝。 – Thompson 2012-04-02 16:39:50

回答

11

這就是你需要做什麼:

select gender, 
     count(case when age between 0 and 20 then 1 else null end) Age_0_20, 
     count(case when age between 21 and 40 then 1 else null end) Age_21_40 
from yourtable 
group by gender 

相應的調整:)

更新,以澄清

注意COUNT聚合函數只能算作非 - 空值。因此,case中的else值必須爲NULLWhen值返回1,但它可能只是任何非空值。

有些人利用SUM實現這個:

select gender, 
     sum(case when age between 0 and 20 then 1 else 0 end) Age_0_20, 
     sum(case when age between 21 and 40 then 1 else 0 end) Age_21_40 
from yourtable 
group by gender 

結果將是完全一樣的。

+0

它返回錯誤**#1064 - 你有一個錯誤!你的SQL語法;檢查與您的MySQL服務器版本相對應的手冊,以便在'than 1 else 0 end'附近使用正確的語法)Age_0_19,總和(在第2行時年齡在20到40之間的情況比1 e''** – Thompson 2012-04-02 16:20:32

+4

剛剛寫了'而不是'then'? – 2012-04-02 16:21:09

+0

哎呀!對不起,我寫了**而不是**,然後是**,因爲它已經給錯誤了#1064 - 你的SQL語法有錯誤;請檢查手冊,它對應於你的MySQL服務器版本的正確語法,用於在第4行'group by gender'附近使用** – Thompson 2012-04-02 16:23:08