2017-08-05 60 views
1

我有一個表logins下面的模式獲取最大計數最高計數,表中每個user_id的MySQL從一個子查詢組

我嘗試以下查詢:

SELECT MAX(num) as max_num, user_id, weekday 
FROM (
    SELECT COUNT(*) as num, user_id, weekday 
    FROM logins 
    GROUP BY user_id, weekday 
) C 
WHERE user_id = C.user_id AND num = C.num 
GROUP BY user_id; 

這讓我weekday = 1,而不是2。我認爲我不應該在這裏使用WHERE條款,但我無法設法得到正確的結果。

我檢查了,沒有運氣其他類似的問題,如:

我創建了一個SQL撥弄我的例子:http://sqlfiddle.com/#!9/e43a71/1

回答

0

這是上午ethod:

SELECT user_id, MAX(num) as max_num, 
     SUBSTRING_INDEX(GROUP_CONCAT(weekday ORDER BY num DESC), ',', 1) as weekday_max 
FROM (SELECT user_id, weekday, COUNT(*) as num 
     FROM logins l 
     GROUP BY user_id, weekday 
    ) uw 
GROUP BY user_id; 
+0

注意'COUNT(*)'可能並不總是完全用在InnoDB由於這只是現在固定在MySQL 19年7月5日的錯誤工作。我之前遇到過這個問題。似乎升級到5.7.19後工作正常。 https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-19.html –

+0

@Marc。 。 。你真的更喜歡這個的其他答案? –

0
SELECT days.user_id, days.weekday, days.num 
FROM (
    SELECT user_id, MAX(num) AS num 
    FROM (
     SELECT user_id, weekday, COUNT(*) AS num 
     FROM logins 
     GROUP BY user_id, weekday 
    ) max 
    GROUP BY user_id 
) nums 
JOIN (
    SELECT user_id, weekday, COUNT(*) as num 
    FROM logins 
    GROUP BY user_id, weekday 
) days ON(days.user_id = nums.user_id AND days.num = nums.num); 

-- With Mariadb 10.2 or MySQL 8.0.2 
WITH days AS (
    SELECT user_id, weekday, COUNT(*) as num 
    FROM logins 
    GROUP BY user_id, weekday 
) 
SELECT days.user_id, days.weekday, days.num 
FROM (
    SELECT user_id, MAX(num) AS num 
    FROM days 
    GROUP BY user_id 
) nums 
JOIN days ON(days.user_id = nums.user_id AND days.num = nums.num); 
+0

如果您有Mariadb 10.2或MySQL 8.0.2+,則可以使用窗口函數或WITH statment編寫更好和更短的查詢。 –