简体   繁体   中英

How to join a SQL table while doing a count for the most rows?

So I have a "bookmark" table for which i am trying to get the "UserID"s of the users that have bookmark the most content. This query returns the UserID of the ten most active users. This query looks like this for me and works:

SELECT COUNT(*) AS `Rows`, UserID FROM `bookmark`
WHERE UserID NOT IN(1, 2, 25, 38, 41, 43, 47, 125) 
GROUP BY UserID ORDER BY `Rows` DESC LIMIT 10 

Now i am trying to join the result queries to the "accounts" table to get all the info of each user ID by comparing the UserID to the "id" in the accounts table.

SELECT COUNT(*) AS `Rows`, UserID FROM `bookmark`
join accounts ON accounts.ID = bookmark.UserID
WHERE UserID NOT IN(1, 2, 25, 38, 41, 43, 47, 125) 
GROUP BY UserID ORDER BY `Rows` DESC LIMIT 10 

This is not returning any of the rows as the accounts table but is instead returning the same result as before. I need to be able to get all the rows of the accounts table (same thing as using *)

If it helps my accounts table has these rows = user_name, id, email and my bookmark table has these rows = id, UserId, link

One solution is to move the group by to a subquery:

select  *
from    (
        select  count(*) as Rows
        ,       UserID 
        from    bookmark
        where   UserID not in (1, 2, 25, 38, 41, 43, 47, 125) 
        group by
                UserID 
        ) as BookmarkSubquery
join    accounts
on      accounts.ID = BookmarkSubquery.UserID
order by
        BookmarkSubquery.Rows DESC 
limit   10 

Another is to add the columns from accounts to the group by:

select  count(*) as Rows
,       bookmark.UserID 
,       accounts.Name
,       accounts.BirthDate
from    bookmark
join    accounts
on      accounts.ID = BookmarkSubquery.UserID
where   bookmark.UserID not in (1, 2, 25, 38, 41, 43, 47, 125) 
group by
,       bookmark.UserID 
,       accounts.Name
,       accounts.BirthDate
order by
        count(*) DESC 
limit   10 

Note: MySQL allows you to list only bookmark.UserID in the group by ; although that will work, it's not recommended.

This may be ugly but you could store the first query in a temporary table, then do a join between accounts and your temporary table.

Also, try doing a left join to see if you get anything that way. Sometimes that helps in debugging the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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