php - 如何在计算最多行的同时加入 SQL 表?

标签 php mysql sql

所以我有一个“书签”表,我试图为它获取拥有最多内容书签的用户的“UserID”。此查询返回十个最活跃用户的 UserID。这个查询对我来说看起来像这样并且有效:

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 

现在我尝试将结果查询加入到“accounts”表中,通过将 UserID 与 accounts 表中的“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 

这不会像帐户表那样返回任何行,而是返回与以前相同的结果。我需要能够获取帐户表的所有行(与使用 * 相同)

如果它有助于我的帐户表有这些行 = user_name、id、电子邮件,我的书签表有这些行 = id、UserId、链接

最佳答案

一个解决方案是将 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 

另一种方法是将帐户中的列添加到组中:

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 

注意:MySQL 只允许您在group by 中列出bookmark.UserID;虽然这会起作用,但不推荐这样做。

关于php - 如何在计算最多行的同时加入 SQL 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6878766/

相关文章:

php - 将 html 输入值转换为下载函数的 $variable

mysql - 将mysql数据传输到新的数据库结构

php - PDO 连接池与 AJAX

sql - 删除 SQL 命令中的毫秒数

php - 对特定页面使用包含和样式表?

php - Zend 框架 : Plugin paths

Mysql 错误 #1054 - 更新时 'Y' 中的未知列 'where clause'

mysql - Doctrine2 - 哪种方法更合适?

sql - 如何在 sql server 2005 中使用检查约束

php - Spotify 自动播放列表管理与 PHP 后端和速率限制