读书人

帮忙看看如何简化这条mysql语句并

发布时间: 2013-12-23 14:30:52 作者: rapoo

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


现在要对每个部门的得分情况进行查询并统计,即使某个部门没有得分纪录也要显示他的得分(0分),查询统计的结果如下所示:
帮忙看看,如何简化这条mysql语句,并且优化查询效率~

mysql语句一直一知半解,东拼西凑写了一段:

select 
'' as type,
`class`.`name` as cname,
`score`.`cid`,
`score`.`uid`,
`user`.`name` as uname,
`score`
from `score`
right join `class` on `score`.`cid` = `class`.`cid`
left join `user` on `score`.`uid` = `user`.`uid`

union all(
select
'汇总',
`c`.`cname`,
`c`.`cid`,
`c`.`uid`,
count(`cid`) as uname,
sum(`score`) as score
from (
select
'' as type,
`class`.`name` as cname,
`score`.`cid`,
`score`.`uid`,
`user`.`name` as uname,
`score`
from `score`
right join `class` on `score`.`cid` = `class`.`cid`
left join `user` on `score`.`uid` = `user`.`uid`
) c group by `cname`
)

order by `cname` asc, `type` asc;


貌似这个sql语句太复杂了!能不能简化这条语句呢?另外从查询效率上能不能优化?
表结构、数据和代码都在这里:http://sqlfiddle.com/#!2/6f5db6/10
请帮忙看看
[解决办法]
可以用一句简单的sql + 一段php程序进行实现吗
[解决办法]
desc sql
对关键字段,加上索引看看

读书人网 >PHP

热点推荐