Let's take a look at how to simplify this mysql statement and optimize the query efficiency ~~~~~

Source: Internet
Author: User
Let's take a look at how to simplify this mysql statement and optimize the query efficiency ~~~~~ This post was last edited by setoy at 12:03:34

There are three tables: the administrator table, the department table, and the score table for the department as follows:


Now you need to query and count the scores of each department. even if a department does not have a score record, the score (0 points) is displayed. the query result is as follows:


The mysql statement has been completely confusing and I have written a piece of code:
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 'summary', '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;


It seems that this SQL statement is too complicated! Can this statement be simplified? In addition, can the query efficiency be optimized?
Table structure, data, and code are all here: http://sqlfiddle.com /#! 2/6f5db6/10
Please take a look


Reply to discussion (solution)

Can I use a simple SQL statement and a php program for implementation?

Desc SQL
Add an index to the keyword field.

Desc SQL
Can I add an index to the keyword field to see if it is specific?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.