所以我有一个“书签”表,我试图为它获取拥有最多内容书签的用户的“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/