比较一个查询中两个mysql查询的计数

时间:2016-07-01 06:35:19

标签: mysql

我在mysql查询中遇到了一些问题。我有两个查询,两个都返回结果很好。

我的要求是我想在一个查询中使用这两个查询,以便我可以比较两个查询的计数。

第一次查询

SELECT 
      user_profile.USERID, 
      user_profile.FIRSTNAME, 
      user_profile.LASTNAME,
      lastvisit.lastvisit,
      lastvisit.SOURCE as "RegistrationPlatform"  
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(lastvisit.lastvisit) = 5 AND YEAR(lastvisit.lastvisit) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')

第二次查询

SELECT 
      user_profile.USERID, 
      user_profile.FIRSTNAME, 
      user_profile.LASTNAME,
      user_profile.registrationDate,
      lastvisit.SOURCE as "RegistrationPlatform"  
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(user_profile.registrationDate) = 5 AND YEAR(user_profile.registrationDate) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')

输出应该是这样的

Query   UserCount
Query1  100
Query2  200 

有什么建议吗?

由于

1 个答案:

答案 0 :(得分:1)

使用Count(*)Union

SELECT 
    'query1' as query
    Count(*) as UserCount
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(lastvisit.lastvisit) = 5 AND YEAR(lastvisit.lastvisit) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')
UNION
SELECT 
    'query2' as query
    Count(*)
    FROM user_profile
    INNER JOIN lastvisit
   ON user_profile.USERID =lastvisit.USERID
    WHERE MONTH(user_profile.registrationDate) = 5 AND YEAR(user_profile.registrationDate) = 2016
    AND lastvisit.SOURCE IN ('Online', 'MobileApp')