2014-10-31 59 views
1

我是MySQL的初學者,我需要編寫查詢來選擇事件表中的所有行並計算在此事件中有多少用戶註冊(但我需要按性別分割用戶)。MySQL查詢 - 統計有多少用戶在事件(男性和女性)上註冊

我的表:

表事件:

id 
event_name 
...and another insignificant column 

表用戶:

id 
username 
gender (allowed values: male or female) 
...and another insignificant column 

表user_on_event:

event_id (link to event table to column ID) 
user_id (link to user table to column ID) 

與此查詢:

SELECT *, COUNT(user_on_event.user_id) as total_registred_users_on_event FROM event LEFT JOIN user_on_event ON user_on_event.event_id = event.id 

這將選擇一切從事件表和計數所有註冊用戶。這是好的,但我還需要計數登記的女性和男性。

如何在我的查詢中修改以實現此目的?

回答

2
select 
    sum(gender = 'male') male_count, 
    sum(gender = 'female') female_count, 
    count(*) total_count 
from user_on_event uoe 
join user u on u.id = uoe.user_id 

,如果你想爲一個特定的事件數增加

where uoe.event_id = :event_id 
1

也許我已經得到它:)這個查詢看起來好嗎?你怎麼看?

SELECT *, COUNT(user_on_event.user_id) as total_registred_users_on_event, 
(SELECT COUNT(user.id) FROM user WHERE user.id = user_on_event.user_id 
AND user.gender = "male") as men, 
(SELECT COUNT(user.id) FROM user 
WHERE user.id = user_on_event.user_id 
AND user.gender = "female") as women FROM event 
LEFT JOIN user_on_event ON user_on_event.event_id = event.id; 
1
SELECT event.id, event_name, gender, COUNT(*) from event 
INNER JOIN user_on_event ON event_id = event.id 
INNER JOIN user ON user.id = user_id 
GROUP BY event.id, event_name, gender 

如果你選擇計數兩次+選擇該查詢只掃描表一次,而不是3倍*。但是你會看到每個事件1-2行,一個男人一個女人。

相關問題