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 ~~~~~ At last, this post was edited by setoy from 2013-12-1912: 03: 34 and has three tables: the administrator table, department table, and the administrator's score table for the department, as shown below: now we need to query the scores of each department and make statistics to help us see how to simplify this mysql statement and optimize the query efficiency ~~~~~
At the end of this post, setoy edited three tables at 12:03:34 on: The administrator table, department table, and the score table of the administrator for the department, as shown below:


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 and share it with us: More

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.