mysql多表统计查询排序

dzhlin 2014-10-27 03:45:09
现在有三张表,一张是学生表,学号是唯一索引,二是学生签到表,学生每次签到都一条记录,三是学生留言表,每次留言都有一条记录,现在想查询学生信息,并统计出每个学生签到和留言的总数作为一个字段total加到学生信息中,并根据total降序排序,用一条sql语句怎么做到啊,新学mysql,不懂,求大神们帮帮忙?
...全文
425 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
snartssy2 2015-04-27
  • 打赏
  • 举报
回复
引用 1 楼 roundman 的回复:

select 学号,count(签到)+ count(留言) as total
from 学生 a,签到 b,留言 c
on a.学号 = b.学号
and a.学号 = c.学号
group by 学号
order by total desc
 
多表查询,如果要查询的字段不止一个表中有,应指定是哪个表中的字段。应指定“学号”是哪个表的
ACMAIN_CHM 2014-10-27
  • 打赏
  • 举报
回复
select s.stuid, s.Nmae, (select count(*) from check where stuid = s.stuid) + (select count(*) from liuyan where stuid = s.stuid) from stu s order by 3 desc
roundman 2014-10-27
  • 打赏
  • 举报
回复
引用 5 楼 u012576096 的回复:
谢谢你们的回复,按照1#(不知道怎么直接在1#回复)的运行,需要学生同时签到并且有留言才可以实现,可是有些学生是没有留言的。3#的我看不懂。我自己写的:
select s.*,from stu s order by (select count(c.id) from check c where c.stuid = s.stuid)+(select count(l.id) from liuyan l where l.stuid = s.stuid) desc
不知道可以吗?
不用啊,没有留言的话,count出来会是0的,不影响。
dzhlin 2014-10-27
  • 打赏
  • 举报
回复
total就不知道怎么写,所以就不要了
dzhlin 2014-10-27
  • 打赏
  • 举报
回复
谢谢你们的回复,按照1#(不知道怎么直接在1#回复)的运行,需要学生同时签到并且有留言才可以实现,可是有些学生是没有留言的。3#的我看不懂。我自己写的:
select s.*,from stu s order by (select count(c.id) from check c where c.stuid = s.stuid)+(select count(l.id) from liuyan l where l.stuid = s.stuid) desc
不知道可以吗?
moon0312 2014-10-27
  • 打赏
  • 举报
回复
引用 3 楼 moon0312 的回复:
-- 学生表A ,签到B,留言C UPDATE A SET A.total = B.total INNER JOIN ( SELECT B.studentnum,(B.count(*)+C.count(*)) AS total FROM B,C WHERE B.studentnum = C.studentnum) D ON A.studentnum = D.studentnum;
UPDATE A SET A.total = B.total INNER JOIN ( SELECT B.studentnum,(B.count(*)+C.count(*)) AS total FROM B,C WHERE B.studentnum = C.studentnum GROUP BY studentnum ) D ON A.studentnum = D.studentnum
moon0312 2014-10-27
  • 打赏
  • 举报
回复
-- 学生表A ,签到B,留言C UPDATE A SET A.total = B.total INNER JOIN ( SELECT B.studentnum,(B.count(*)+C.count(*)) AS total FROM B,C WHERE B.studentnum = C.studentnum) D ON A.studentnum = D.studentnum;
roundman 2014-10-27
  • 打赏
  • 举报
回复
引用 1 楼 roundman 的回复:

select 学号,count(签到)+ count(留言) as total
from 学生 a,签到 b,留言 c
on a.学号 = b.学号
and a.学号 = c.学号
group by 学号
order by total desc
 
写错了,on改成where
roundman 2014-10-27
  • 打赏
  • 举报
回复

select 学号,count(签到)+ count(留言) as total
from 学生 a,签到 b,留言 c
on a.学号 = b.学号
and a.学号 = c.学号
group by 学号
order by total desc
 

56,677

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧