mysql多表统计查询排序

MySql 码拜 10年前 (2014-04-27) 1654次浏览 0个评论

现在有三张表,一张是学生表,学号是唯一索引,二是学生签到表,学生每次签到都一条记录,三是学生留言表,每次留言都有一条记录,现在想查询学生信息,并统计出每个学生签到和留言的总数作为一个字段total加到学生信息中,并根据total降序排序,用一条sql语句怎么做到啊,新学mysql,不懂,求大神们帮帮忙?

10分
select 学号,count(签到)+ count(留言) as total
from 学生 a,签到 b,留言 c
on a.学号 = b.学号
and a.学号 = c.学号
group by 学号
order by total desc
 
引用 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

— 学生表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;
10分
引用 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

谢谢你们的回复,按照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

不知道可以吗?

total就不知道怎么写,所以就不要了
10分
引用 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的,不影响。

10分
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
引用 1 楼 roundman 的回复:
select 学号,count(签到)+ count(留言) as total
from 学生 a,签到 b,留言 c
on a.学号 = b.学号
and a.学号 = c.学号
group by 学号
order by total desc
 

多表查询,如果要查询的字段不止一个表中有,应指定是哪个表中的字段。应指定“学号”是哪个表的


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明mysql多表统计查询排序
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!