任务获取最多参与问题

有两个表tasks和users,加了个多对多的关系用来获取任务的参与者,中间表是task_user。现在有一个需求要获取参与人数最多的一条任务。我现在的方法是用一条sql语句实现的:

SELECT * from tasks order by (select count(id) from task_user where task_user.task_id = tasks.id) DESC limit 1<br></br>

不过这样的话任务多了,会执行很多次

select count(id) from task_user where task_user.task_id = tasks.id<br></br>

大家帮忙看下有没有别的解决办法,sql语句方面是我的弱项。。

group by试试看呢?我也是个数据库渣= =

daryl

group by试试看呢?我也是个数据库渣= =

perfectboook

@daryl 表示从来没有用过group by。。查文档写出来一句:

select tasks.id,task_user.task_id ,count(task_user.task_id) as counts from tasks , task_user group by tasks.id HAVING tasks.id = task_user.task_id order by counts desc limit 1

貌似好多了。

perfectboook

擦,才发现写错了。修正后代码为:

SELECT task_id as id,count(user_id) as count from task_user GROUP BY task_id ORDER BY count desc LIMIT 1