这是我的查询:
select u.id, u.name,
(select count(*) from users where name = u.name) as total
from users u
where u.name = 'anything'
order by id
limit 1
如您所知,我的查询返回 1 个具有任意
名称的用户。 total
包含具有anything
名称的所有用户的数量。好的,一切都好。
现在,当查询中有三个 JOIN
时,我想做同样的事情。请假设:
select u.id, u.name, sum(r.reputation) rep
from users u
join reputation r on u.id = r.user_id
join posts_tags pt on r.post_id = pt.post_id
join tags t on pt.tag_id = t.id
where u.name = 'anything' and t.name = 'mytag'
group by u.id, u.name
order by rep desc, u.id
limit 1
现在我想知道,如何在此 ^ 查询中实现 total
部分?
最佳答案
尝试这个查询,希望这能给您正确的结果。
select * , count(id) as total from (select u.id, u.name, sum(r.reputation) rep
from users u
join reputation r on u.id = r.user_id
join posts_tags pt on r.post_id = pt.post_id
join tags t on pt.tag_id = t.id
where u.name = 'anything' and t.name = 'mytag'
group by u.id, u.name
order by rep desc, u.id
limit 1 ) as result
关于mysql - 当同时存在 LIMIT 和 JOIN 子句时,如何计算所有行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476858/