A single SELECT statement to realize the number of Mysql query statistics _mysql

Source: Internet
Author: User
Tags mysql query

The number of MySQL query statistics implemented by single SELECT statement

How is the use of a single SELECT statement to realize the number of MySQL query statistics? Use too much, such as a report card, you have to check the number of people and the number of failed, how to query out?
MySQL Query statistics number of simple statements must be this:

Copy Code code as follows:

Select A.name,count_neg,count_plus from
(select count (ID) as Count_plus,name from Score2 where score >=60 Group by name) A,
(select count (ID) as Count_neg,name from Score2 where score <=60 GROUP by name) b
where A.name=b.name

That is, you must use at least 2 statements.

Today happened to find MySQL support if, then creatively use if to achieve it:

Copy Code code as follows:

Select Name, SUM (if (score>=60,1,0)), SUM (if (score<60,1,0)) from Score2 GROUP by name

How to achieve MySQL query statistics by a single SELECT statement simple.

The principle is to be greater than 60 and assign a value of 1, then sum is counted.

Count in the MySQL query statistics function

Today I came across a topic: Statistics of all female students with a total score greater than 90
I have just started to write: $sql = "Select Girls ' results from the use where score >"; $result = mysql_query ($sql);
$row = mysql_num_rows ($result); echo "total: $row";
But 100 is OK, if it is 10,000, it is not to be very slow AH!! Later a friend told me to use the Count function, which I just remembered.
Change the SQL statement above to read:
$sql = "SELECT count (*), female students ' results from the use Group by female results > 90";
So the query statement is much faster.

Related Article

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.