2016-07-01 132 views
-2

我已經卡住了一些在mysql查詢中的位置。我有兩個查詢,都返回結果罰款。在一個查詢中比較兩個mysql查詢的計數

我的要求是我想在一個查詢中使用兩個查詢,以便我可以比較兩個查詢的數量。

1查詢

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 

任何建議嗎?

感謝

+0

顯示的查詢和一些示例數據與預期的結果 – Jens

+0

請檢查該http://stackoverflow.com/help/how-to-ask –

+0

的第一聯盟(第一個區塊)的列名是爲最終輸出而冰凍的 – Drew

回答

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')