简体   繁体   English

MySQL查询联接3个表并计数

[英]MySQL query joining 3 tables and counting

I've been stuck on this problem for far too long. 我一直在这个问题上停留太久了。
I have to merge 3 tables and do some counting of distinct values. 我必须合并3个表,并对不同的值进行一些计数。
I have 3 tables 我有3张桌子
1.User_me 1.User_me
profileId( String ) profileId(String)
responded( int 1 or 0) 已回应(int 1或0)

2.Profiles 2.Profiles
profileId ( String ) profileId(String)
idLocation ( int ) idLocation(int)

3.lookup_location 3.lookup_location
id ( int ) id(int)
location (String ) 位置(字符串)

I can join User_me and Profiles ON User_me.profileId = Profiles.profileId 我可以加入User_me和个人档案ON User_me.profileId = Profiles.profileId
I can join Profiles and lookup_location ON Profiles.idLocation = lookup_location.id 我可以加入Profiles和lookup_location ON Profiles.idLocation = lookup_location.id

Under Profiles I need to count the number of distinct values for idLocation where User_me.profileId = Profiles.profileId 在“个人档案”下,我需要计算idLocation的不同值的数量,其中User_me.profileId = Profiles.profileId
I also need to count the number of Profiles.idLocation that have User_me.responded = 1 我还需要计算User_me.responded = 1的Profiles.idLocation的数量

I have this: 我有这个:

SELECT lookup.location, count(*) as total
FROM User_me user
JOIN Profiles
  ON user.profileId= profiles.profileId
JOIN lookup_location lookup
  ON profiles.idLocation = lookup.id
GROUP BY profiles.idLocation

but I still need to have the column giving me the count where User_me.responded = 1 但我仍然需要该列为我提供其中User_me.responded = 1的计数
Something like: 就像是:

SELECT lookup.location, count(*) as total, count(*) responded

If I'm understanding your question correctly, you can you a case statement in the count aggregate: 如果我正确理解了您的问题,则可以在count汇总中使用case陈述:

SELECT lookup.location, count(*) as total, 
    count(case when user.responded = 1 then 1 end) as responded
FROM User_me user
JOIN Profiles
  ON user.profileId= profiles.profileId
JOIN lookup_location lookup
  ON profiles.idLocation = lookup.id
GROUP BY profiles.idLocation

Since you're using MySQL , you can also use something like sum(user.responded = 1) . 由于使用的是MySQL ,因此还可以使用sum(user.responded = 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM