幫忙看看,怎麼簡化這條mysql語句,並且最佳化查詢效率~~~~~
本帖最後由 setoy 於 2013-12-19 12:03:34 編輯
有三張表:管理員表,部門表,和管理員對部門的打分表,如下:
現在要對每個部門的得分情況進行查詢並統計,即使某個部門沒有得分紀錄也要顯示他的得分(0分),查詢統計的結果如下所示:
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
對關鍵字段,加上索引看看