我有一个像stackoverflow这样的问答网站。以下是一些表格的结构:
Peter
现在我需要找到特定标签中的顶级用户。例如,我需要在PHP标记中找到PHP
作为顶级用户。因为他对question1 (有ChangeDetectorRef
标签)的回答已经赢得了2个赞成票。这样做可能吗?
答案 0 :(得分:1)
试试这个:
select q1.title, u.id, u.name, sum(v.value) total from `q&a` q1
left join `q&atag` qt ON q1.id = qt.`q&aid`
inner join tags t ON qt.tag_id = t.id
left join `q&a` q2 ON q2.related = q1.id
left join users u ON q2.author_id = u.id
left join votes v ON v.post_id = q2.id
where t.name = 'PHP'
group by q1.id, u.id
这是一个简单的分开的解决方案:
让我们将其划分为子查询:
id
:select id from tags where name = 'PHP'
select 'q&aid' from 'q&aTag' where tag_id = 1.
id
个答案:select id, author_id from
q& a where related in (2.)
select user_id, sum(value) from votes where post_id in (3.) group by user_id
现在将它们组合起来都会产生结果:
select user_id, sum(`value`) total from votes
where post_id in (
select id from `q&a` where related in (
select `q&aid` from `q&aTag` where tag_id IN (
select id from tags where name = 'PHP'
)
)
)
group by user_id
如果您只想要一条记录,可以在最后添加:
order by total desc limit 1