幫忙看看,如何簡化這條mysql語句,並且最佳化查詢效率~

來源:互聯網
上載者:User
幫忙看看,怎麼簡化這條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
對關鍵字段,加上索引看看
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.