帮忙看看,如何简化这条mysql语句,并且优化查询效率~

WBOY
Release: 2016-06-13 11:43:17
Original
807 people have browsed it

帮忙看看,怎么简化这条mysql语句,并且优化查询效率~~~~~

本帖最后由 setoy 于 2013-12-19 12:03:34 编辑 有三张表:管理员表,部门表,和管理员对部门的打分表,如下:


现在要对每个部门的得分情况进行查询并统计,即使某个部门没有得分纪录也要显示他的得分(0分),查询统计的结果如下所示:


mysql语句一直一知半解,东拼西凑写了一段:
select <br />  '' as type, <br />  `class`.`name` as cname, <br />  `score`.`cid`, <br />  `score`.`uid`, <br />  `user`.`name` as uname,<br />  `score`<br />from `score`<br />right join `class` on `score`.`cid` = `class`.`cid`<br />left join `user` on `score`.`uid` = `user`.`uid`<br /><br />union all(<br />  select <br />    '汇总', <br />    `c`.`cname`, <br />    `c`.`cid`, <br />    `c`.`uid`, <br />    count(`cid`) as uname,<br />    sum(`score`) as score<br />  from (<br />    select <br />      '' as type, <br />      `class`.`name` as cname, <br />      `score`.`cid`, <br />      `score`.`uid`, <br />      `user`.`name` as uname,<br />      `score`<br />    from `score`<br />    right join `class` on `score`.`cid` = `class`.`cid`<br />    left join `user` on `score`.`uid` = `user`.`uid`<br />  ) c group by `cname`<br />)<br /><br />order by `cname` asc, `type` asc;
Copy after login


貌似这个sql语句太复杂了!能不能简化这条语句呢?另外从查询效率上能不能优化?
表结构、数据和代码都在这里:http://sqlfiddle.com/#!2/6f5db6/10
请帮忙看看
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template