简体   繁体   English

如何在对最多行进行计数的同时联接SQL表?

[英]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. 因此,我有一个“书签”表,我试图为该表获取具有最多书签内容的用户的“ UserID”。 This query returns the UserID of the ten most active users. 该查询返回十个最活跃用户的UserID。 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. 现在,我尝试将结果查询加入“帐户”表,以通过将用户ID与帐户表中的“ id”进行比较来获取每个用户ID的所有信息。

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. 这不返回任何行作为accounts表,而是返回与之前相同的结果。 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 如果有帮助,我的帐户表中的这些行=用户名,ID,电子邮件,而我的书签表中的这些行= ID,用户ID,链接

One solution is to move the group by to a subquery: 一种解决方案是将group by移动到子查询:

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 ; 注意:MySQL允许您仅列出group by bookmark.UserID 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. 有时,这有助于调试查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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