当前位置:网站首页>MySQL: grouping query

MySQL: grouping query

2022-06-09 07:29:00 Cat fearless mouse a

Group query

1、 Grouping query is to group data according to one or more fields , stay MYSQL Use in GROUP BY Keyword groups data

2、GROUP BY Keyword can group query results by one or more fields . Fields with equal values are a group of
    ⑴ The core of grouping is : In the query SQL Column name of the group specified in , Then group according to the value of the column , A set of equal values

3、 The basic syntax format of group query is as follows :

 GROUP BY  Field name  [HAVING  Conditional expression ]
 Parameters :
1、 Field name : It refers to grouping according to the value of this field ( The grouping is based on the column name )
2、HAVING Conditional expression : Used to limit the display after grouping , The result of the conditional expression will be displayed 

Create grouping

1、 Group data , There are generally two scenarios :
    ⑴ Use alone GROUP BY keyword ,
    ⑵ take GROUP BY Keywords are used with aggregate functions ( Commonly used )

2、 about GROUP BY Use of clauses , The following points need to be noted :
    ⑴GROUP BY Clause can contain any number of columns , Make it possible to nest groups , Provide more detailed control for data grouping
    ⑵GROUP BY Clause must be a search column or a valid expression , But it cannot be an aggregate function . If in SELECT Using expressions in statements , Must be in GROUP BY Clause specifies the same expression

3、 If the column used for grouping contains NULL value , be NULL Will be returned as a separate group ; If there are more than one... In this column NULL value , Then put these NULL The rows in which the values are located are grouped

GROUP BY Use alone

Use alone GROUP BY When a keyword , The query result will only display the first record of each group

example 1: When there is no filter condition

mysql> SELECT * FROM polls_article;
+----+-----------+----------------+-------+--------+----------------------------+
| id | title     | content        | price | author | create_time                |
+----+-----------+----------------+-------+--------+----------------------------+
|  1 |  The romance of The Three Kingdoms   |  Monkey king made a scene in heaven  |   132 |  Wu chengen  | 2020-09-13 14:48:30.000000 |
|  2 |  The romance of The Three Kingdoms 1 |  At the end of the Eastern Han Dynasty, there were three kingdoms  |   154 |  Luo Guanzhong  | 2020-09-13 12:48:30.962070 |
|  3 |  A dream of red mansions     |  Grandma Liu enters the Grand View Garden  |   154 |  Cao xueqin  | 2020-09-13 12:48:30.962070 |
|  4 |  Water margin     |  to join rebels        |   140 |  Shi Naian  | 2020-09-13 12:48:30.962070 |
|  7 | wed       | dwd            |   123 | 44     | 2020-10-13 17:08:50.493488 |
|  8 | ds        | dwd            |   123 | 32     | 2020-10-13 17:19:18.121264 |
|  9 |  Journey to the west     |  To obtain buddhist scriptures        |   345 | NULL   | 2020-11-14 15:48:59.000000 |
+----+-----------+----------------+-------+--------+----------------------------+
7 rows in set (0.00 sec)

--  according to price Fields group data 
mysql> SELECT * FROM polls_article GROUP BY price;
+----+-----------+----------------+-------+--------+----------------------------+
| id | title     | content        | price | author | create_time                |
+----+-----------+----------------+-------+--------+----------------------------+
|  7 | wed       | dwd            |   123 | 44     | 2020-10-13 17:08:50.493488 |
|  1 |  The romance of The Three Kingdoms   |  Monkey king made a scene in heaven  |   132 |  Wu chengen  | 2020-09-13 14:48:30.000000 |
|  4 |  Water margin     |  to join rebels        |   140 |  Shi Naian  | 2020-09-13 12:48:30.962070 |
|  2 |  The romance of The Three Kingdoms 1 |  At the end of the Eastern Han Dynasty, there were three kingdoms  |   154 |  Luo Guanzhong  | 2020-09-13 12:48:30.962070 |
|  9 |  Journey to the west     |  To obtain buddhist scriptures        |   345 | NULL   | 2020-11-14 15:48:59.000000 |
+----+-----------+----------------+-------+--------+----------------------------+
5 rows in set (0.00 sec)

notes :
1、 above SQL Express : Query all data in the table ( All columns 、 That's ok ), And according to the results "price" Field values are grouped
    ⑴ grouping :"price" The fields with the same value are a set of
    ⑵ Because it is used alone GROUP BY keyword , Therefore, only the first record of each group will be returned

example 1_1: When there are filter conditions

mysql> SELECT id,title,price,author FROM polls_article WHERE price > 130;
+----+----------+-------+--------+
| id | title    | price | author |
+----+----------+-------+--------+
|  1 |  The romance of The Three Kingdoms  |   132 |  Wu chengen  |
|  2 |  The romance of The Three Kingdoms  |   154 |  Luo Guanzhong  |
|  3 |  Water margin    |   154 |  Cao xueqin  |
|  4 |  Water margin    |   140 |  Shi Naian  |
|  9 |  Journey to the west    |   345 | NULL   |
+----+----------+-------+--------+
5 rows in set (0.00 sec)

mysql> SELECT id,title,price,author FROM polls_article WHERE price > 130 GROUP BY title;
+----+----------+-------+--------+
| id | title    | price | author |
+----+----------+-------+--------+
|  1 |  The romance of The Three Kingdoms  |   132 |  Wu chengen  |
|  3 |  Water margin    |   154 |  Cao xueqin  |
|  9 |  Journey to the west    |   345 | NULL   |
+----+----------+-------+--------+
3 rows in set (0.00 sec)

notes :
1、 In this case SQL Express : In the query table "price > 130" The data of ( Some columns of the query ), Where to find the data that meets the conditions "title" Field values are grouped
    ⑴ Find the data that meets the filtering conditions first , And then group it up

2、 In the previous two examples : Use alone GROUP BY Keyword displays only one record for each group
    ⑴ This explanation :GROUP BY When keywords are used alone , Only one record of each group can be queried
    ⑵ It doesn't make much sense . therefore , Generally, it is only used when using set functions GROUP BY keyword

GROUP BY And aggregate functions

1、GROUP BY Keywords are usually used with set functions . Set functions include COUNT() function 、SUM() function 、AVG() function 、MAX() Functions and MIN() function

2、 If GROUP BY Not used with aggregate functions , The query result is the grouping of field values
    ⑴ Records with the same value in the field are a group , But only the first record of the group is displayed ( Follow the front GROUP BY Use it alone )

3、 Common aggregate functions are :
    ⑴COUNT() function : Number of records used for statistics
    ⑵SUM() function : Used to calculate the sum of the values of the field
    ⑶AVG() function : The average value used to calculate the value of the field
    ⑷MAX() function : The maximum value used to query the field
    ⑸MIN() function : The minimum value for the query field

example 2:

mysql> SELECT * FROM polls_article;
+----+----------+----------------+-------+--------+----------------------------+
| id | title    | content        | price | author | create_time                |
+----+----------+----------------+-------+--------+----------------------------+
|  1 |  The romance of The Three Kingdoms  |  Monkey king made a scene in heaven  |   123 |  Wu chengen  | 2020-09-13 14:48:30.000000 |
|  2 |  The romance of The Three Kingdoms  |  At the end of the Eastern Han Dynasty, there were three kingdoms  |   154 |  Luo Guanzhong  | 2020-09-13 12:48:30.962070 |
|  3 |  Water margin    |  Grandma Liu enters the Grand View Garden  |   154 |  Cao xueqin  | 2020-09-13 12:48:30.962070 |
|  4 |  Water margin    |  to join rebels        |   140 |  Shi Naian  | 2020-09-13 12:48:30.962070 |
|  7 | wed      | dwd            |   123 | 44     | 2020-10-13 17:08:50.493488 |
|  8 | ds       | dwd            |   123 | 32     | 2020-10-13 17:19:18.121264 |
|  9 |  Journey to the west    |  To obtain buddhist scriptures        |   345 | NULL   | 2020-11-14 15:48:59.000000 |
+----+----------+----------------+-------+--------+----------------------------+
7 rows in set (0.00 sec)

--  Search for books with the same price 
mysql> SELECT price, COUNT(*) FROM polls_article GROUP BY price;
+-------+----------+
| price | COUNT(*) |
+-------+----------+
|   123 |        3 |
|   140 |        1 |
|   154 |        2 |
|   345 |        1 |
+-------+----------+
4 rows in set (0.00 sec)

notes :
1、 The above example shows : Query all the data in the table , according to "price" Field values are grouped , Then calculate the number of records in each group

2、 When creating groups, you need to pay attention to , Generally speaking :
    ⑴ In addition to aggregate functions ,SELECT Each column in the statement must be in the GROUP BY Given in Clause

GROUP BY And GROUP_CONCAT

GROUP BY Keywords can be similar to GROUP_CONCAT() Functions together .GROUP_CONCAT() The function will display the field values of each group

example 3:

mysql> SELECT title,price, COUNT(*) FROM polls_article GROUP BY price;
+----------+-------+----------+
| title    | price | COUNT(*) |
+----------+-------+----------+
|  The romance of The Three Kingdoms  |   123 |        3 |
|  Water margin    |   140 |        1 |
|  The romance of The Three Kingdoms  |   154 |        2 |
|  Journey to the west    |   345 |        1 |
+----------+-------+----------+
4 rows in set (0.00 sec)

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,wed,ds |
|   140 |        1 |  Water margin           |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
4 rows in set (0.00 sec)

notes : It can be seen that
1、 After grouping the data , If you directly query a column : Only the first value in the group will be returned ( In the example title Column )

2、 While using GROUP_CONCAT() function , All the values in the group will be returned

Multi field grouping

1、 Use GROUP BY Multiple fields can be grouped ,GROUP BY Keywords are followed by fields that need to be grouped
2、MYSQL Hierarchical grouping according to the values of multiple fields , The grouping hierarchy is from left to right
    ⑴ That is, first group by the first field , Then in the first record with the same field value , Then group according to the value of the second field ... One analogy
    
example 4:

mysql> SELECT * FROM polls_article;
+----+----------+----------------+-------+--------+----------------------------+
| id | title    | content        | price | author | create_time                |
+----+----------+----------------+-------+--------+----------------------------+
|  1 |  The romance of The Three Kingdoms  |  Monkey king made a scene in heaven  |   123 |  Wu chengen  | 2020-09-13 14:48:30.000000 |
|  2 |  The romance of The Three Kingdoms  |  At the end of the Eastern Han Dynasty, there were three kingdoms  |   154 |  Luo Guanzhong  | 2020-09-13 12:48:30.962070 |
|  3 |  Water margin    |  Grandma Liu enters the Grand View Garden  |   154 |  Cao xueqin  | 2020-09-13 12:48:30.962070 |
|  4 |  Water margin    |  to join rebels        |   140 |  Shi Naian  | 2020-09-13 12:48:30.962070 |
|  7 | ds       | dwd            |   123 | 44     | 2020-10-13 17:08:50.493488 |
|  8 | ds       | dwd            |   123 | 32     | 2020-10-13 17:19:18.121264 |
|  9 |  Journey to the west    |  To obtain buddhist scriptures        |   345 | NULL   | 2020-11-14 15:48:59.000000 |
+----+----------+----------------+-------+--------+----------------------------+
7 rows in set (0.00 sec)

mysql> SELECT * FROM polls_article GROUP BY price,title;
+----+----------+----------------+-------+--------+----------------------------+
| id | title    | content        | price | author | create_time                |
+----+----------+----------------+-------+--------+----------------------------+
|  7 | ds       | dwd            |   123 | 44     | 2020-10-13 17:08:50.493488 |
|  1 |  The romance of The Three Kingdoms  |  Monkey king made a scene in heaven  |   123 |  Wu chengen  | 2020-09-13 14:48:30.000000 |
|  4 |  Water margin    |  to join rebels        |   140 |  Shi Naian  | 2020-09-13 12:48:30.962070 |
|  2 |  The romance of The Three Kingdoms  |  At the end of the Eastern Han Dynasty, there were three kingdoms  |   154 |  Luo Guanzhong  | 2020-09-13 12:48:30.962070 |
|  3 |  Water margin    |  Grandma Liu enters the Grand View Garden  |   154 |  Cao xueqin  | 2020-09-13 12:48:30.962070 |
|  9 |  Journey to the west    |  To obtain buddhist scriptures        |   345 | NULL   | 2020-11-14 15:48:59.000000 |
+----+----------+----------------+-------+--------+----------------------------+
6 rows in set (0.00 sec)

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title)  FROM polls_article GROUP BY price,title;
+-------+----------+---------------------+
| price | COUNT(*) | GROUP_CONCAT(title) |
+-------+----------+---------------------+
|   123 |        2 | ds,ds               |
|   123 |        1 |  The romance of The Three Kingdoms             |
|   140 |        1 |  Water margin               |
|   154 |        1 |  The romance of The Three Kingdoms             |
|   154 |        1 |  Water margin               |
|   345 |        1 |  Journey to the west               |
+-------+----------+---------------------+
6 rows in set (0.00 sec)

notes : In the example above
1、 Express : First according to "price" Field grouping , Press again "title" Field grouping
    ⑴ such as : according to "price" When grouping fields , There are three pieces of data :ds、ds、 Journey to the west
    ⑵ At this point, after grouping : Data with the same value exists in the group
    ⑶ Therefore, these three data continue to follow "title" Field grouping

Use HAVING Filter grouping

1、GROUP BY You can talk to HAVING Together define the conditions to be met for the display record : Only groups that meet the conditions will be displayed

2、HAVING Keywords are used to filter grouping results .WHERE Keywords are used to filter table data
    ⑴ When both exist at the same time : It must be calculated first WHERE,WHERE The excluded records will not appear in the group

example 5:

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds  |
|   140 |        1 |  Water margin           |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
4 rows in set (0.00 sec)

--  Data according to price grouping , Count the number of each group after returning to the group , The number of returned groups is greater than or equal to 2 Group data for 
mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price HAVING COUNT(title) >=2;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds  |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
+-------+----------+-----------------+
2 rows in set (0.00 sec)

example 5_1:

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article WHERE price >130 GROUP BY price;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   140 |        1 |  Water margin           |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
3 rows in set (0.00 sec)

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article WHERE price >130 GROUP BY price HAVING COUNT(title) >=2;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
+-------+----------+-----------------+
1 row in set (0.00 sec)

notes :
above SQL Express : In the query table "price >130" The data of (WHERE)-> according to "price" grouping -> The number of returned group data is greater than or equal to 2 Group (HAVING)

GROUP BY And WITH ROLLUP

WITH POLLUP Keyword is used to add a record at the end of all records , This record is the sum of all the above records , That is, count the number of records

example 6:

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds  |
|   140 |        1 |  Water margin           |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
4 rows in set (0.00 sec)

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price WITH ROLLUP;
+-------+----------+----------------------------------------------+
| price | COUNT(*) | article_title                                |
+-------+----------+----------------------------------------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds                               |
|   140 |        1 |  Water margin                                        |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin                               |
|   345 |        1 |  Journey to the west                                        |
|  NULL |        7 |  The romance of The Three Kingdoms ,ds,ds, Water margin , The romance of The Three Kingdoms , Water margin , Journey to the west  |
+-------+----------+----------------------------------------------+
5 rows in set (0.00 sec)

notes :
adopt GROUP BY After grouping , A new line is added at the end of the display result , The value of each column in this row is exactly the sum of all the above values

GROUP BY And ORDER BY

1、 In some cases, you need to sort the groups
    ⑴ In general ORDER BY It is used to sort query results . When it comes to GROUP BY When used together , You can sort the grouping results

2、 We need to pay attention to : When using ROLLUP when , You can't use it at the same time ORDER BY Clause to sort the results
    ⑴ namely :ROLLUP and ORDER BY It is an example of mutual exclusion 7:

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds  |
|   140 |        1 |  Water margin           |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
4 rows in set (0.00 sec)

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price ORDER BY article_title;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds  |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   140 |        1 |  Water margin           |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
4 rows in set (0.00 sec)

example 7_1:

mysql> SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price HAVING COUNT(article_title) >= 1;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds  |
|   140 |        1 |  Water margin           |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
4 rows in set (0.00 sec)

mysql>  SELECT price,COUNT(*), GROUP_CONCAT(title) AS article_title FROM polls_article GROUP BY price HAVING COUNT(article_title) >= 1 ORDER BY article_title;
+-------+----------+-----------------+
| price | COUNT(*) | article_title   |
+-------+----------+-----------------+
|   123 |        3 |  The romance of The Three Kingdoms ,ds,ds  |
|   154 |        2 |  The romance of The Three Kingdoms , Water margin  |
|   140 |        1 |  Water margin           |
|   345 |        1 |  Journey to the west           |
+-------+----------+-----------------+
4 rows in set (0.00 sec)

MySQL and Oracle Use GROUP BY The difference between

1、Oracle In the use of group by when , The query field must be a grouping basis or an aggregate function
    ⑴select Any non aggregate function field after the clause should be derived from group by After grouping statements , Otherwise, the syntax will fail to compile
    ⑵ in other words SELECT All query columns after clause ( In addition to aggregate functions ), Should be with GROUP BY The columns after the clause are consistent

2、MySQL There is no such restriction , Will automatically take the first line
    ⑴SELECT All query columns after clause ( In addition to aggregate functions ), It can be done with GROUP BY The columns after the clause are inconsistent
    ⑵ notes : although Mysql There are no restrictions in , But it's writing SQL It's better to promise SELECT All query columns after clause ( In addition to aggregate functions ), Both with GROUP BY The columns after the clause are consistent

example 8:Mysql

mysql> SELECT * FROM FRUITS; -- Query all the data 
+------+--------+---------+
| f_id | f_name | f_price |
+------+--------+---------+
|    1 | apple  | 134     |
|    2 | origen | 333     |
|    3 | caomei | 134     |
|    4 | li     | 334     |
+------+--------+---------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM FRUITS GROUP BY f_price; -- Query all columns : Query columns and GROUP BY Clause column names are inconsistent 
--f_price=134 There are two pieces of data ,mysql In this case, only the first piece of data will be returned 
+------+--------+---------+
| f_id | f_name | f_price |
+------+--------+---------+
|    1 | apple  | 134     |
|    2 | origen | 333     |
|    4 | li     | 334     |
+------+--------+---------+
3 rows in set (0.00 sec)

mysql> SELECT f_name FROM FRUITS GROUP BY f_price;  -- Query specified column : Query columns and GROUP BY Clause column names are inconsistent 
+--------+
| f_name |
+--------+
| apple  |
| origen |
| li     |
+--------+
3 rows in set (0.00 sec)

mysql> SELECT f_name,COUNT(f_price) FROM FRUITS GROUP BY f_price;
+--------+----------------+
| f_name | COUNT(f_price) |
+--------+----------------+
| apple  |              2 |
| origen |              1 |
| li     |              1 |
+--------+----------------+
3 rows in set (0.00 sec)

mysql> SELECT f_name,f_price FROM FRUITS GROUP BY f_price,f_name;
+--------+---------+
| f_name | f_price |
+--------+---------+
| apple  | 134     |
| caomei | 134     |
| origen | 333     |
| li     | 334     |
+--------+---------+
4 rows in set (0.00 sec)

example 8_1:Oracle

SQL> SELECT * FROM FRUITS;  -- Query all the data 

      F_ID F_NAME               F_PRICES
---------- -------------------- --------------------
         3 apple                345
         4 origin               123
         5 APPLE                343
         6 CAOMEI               123

SQL> SELECT * FROM FRUITS GROUP BY f_prices;  -- Query all columns : Query columns and GROUP BY Clause column names are inconsistent 
SELECT * FROM FRUITS GROUP BY f_prices
       *
 The first  1  Line error :
ORA-00979:  No  GROUP BY  expression 


SQL> SELECT f_name FROM FRUITS GROUP BY f_prices;  -- Query specified column : Query columns and GROUP BY Clause column names are inconsistent 
SELECT f_name FROM FRUITS GROUP BY f_prices
       *
 The first  1  Line error :
ORA-00979:  No  GROUP BY  expression 


SQL> SELECT f_name,count(*) FROM FRUITS GROUP BY f_prices;  -- Query specified column : Query columns and GROUP BY Clause column names are inconsistent 
SELECT f_name,count(*) FROM FRUITS GROUP BY f_prices
       *
 The first  1  Line error :
ORA-00979:  No  GROUP BY  expression 


SQL> SELECT f_name,f_prices,count(*) FROM FRUITS GROUP BY f_prices,f_name; -- Query specified column : Query columns and GROUP BY Clause column names are consistent 

F_NAME               F_PRICES               COUNT(*)
-------------------- -------------------- ----------
apple                345                           1
origin               123                           1
APPLE                343                           1
CAOMEI               123                           1

原网站

版权声明
本文为[Cat fearless mouse a]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203021422096300.html