SQL select MAX(COUNT)

后端 未结 5 902
梦如初夏
梦如初夏 2021-01-18 03:54

I\'m trying to select the user who has the MAX microposts count:

SELECT \"name\", count(*) FROM \"users\" 
  INNER JOIN \"microposts\" ON \"microposts\".\"us         


        
相关标签:
5条回答
  • 2021-01-18 04:29
    SELECT x.name, MAX(x.count)
    FROM (
     SELECT "name", count(*)
      FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
      GROUP BY users.id
    ) x
    
    0 讨论(0)
  • 2021-01-18 04:37

    I'd try with a ORDER BY max DESC LIMIT 1, where maximum is the count(*) field. Something like:

    SELECT "name", count(*) maximum FROM "users" 
       INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
    GROUP BY users.id 
    ORDER BY maximum DESC 
    LIMIT 1
    

    I dont' have mysql available now, so I'm doing this on the paper (and it might not work), but it's just an orientation.

    0 讨论(0)
  • 2021-01-18 04:40

    It's pretty simple, you can try:

    SELECT "name", MAX(count_num) FROM 
    (SELECT "name", count(*) as count_num
    FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
    GROUP BY users.id) x
    
    0 讨论(0)
  • 2021-01-18 04:45
    SELECT TOP 1 "name", count(*) AS ItemCount FROM "users" 
    INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
    GROUP BY users.id
    ORDER BY ItemCount DESC
    
    0 讨论(0)
  • 2021-01-18 04:50

    maybe like this:

    SELECT "name", count(*) 
    FROM "users" 
    INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
    GROUP BY users.id
    HAVING COUNT(microposts) = (SELECT COUNT(microposts) 
                             FROM   users
                             GROUP  BY microposts
                             ORDER  BY COUNT(microposts) DESC 
                             LIMIT  1) 
    

    Didn't test it, but it might work

    0 讨论(0)
提交回复
热议问题