MySQL data query SQL

MySQL data query SQL

SQL query statement: SELECT

First give a table

Insert picture description here

Retrieve data select


Retrieve a single column

select 字段 from tbname;
# 例: select name from stu;

If there is no clear ordering rule, the order of the returned data, then the order of the returned data has no special meaning.

The order in which the data is returned may or may not be the order in which the data is added to the table. As long as the same number is returned, it is normal.

Retrieve multiple columns

select 字段1,字段2,... from tbname;
# 例: select id,name,age,sex from stu;

When selecting multiple columns, be sure to add a comma between the column names, but do not add a comma after the last column name.

If you add a comma after the last column name, an error will occur.

Retrieve all columns

select * from tbname;
# 例: select * from stu;

Generally do not use wildcards, unless you really need each column in the table, it is best not to use * wildcards.

Use wildcards to retrieve columns with unknown names

DISTINCT of different lines of inspection

select distinct 字段1,字段2... from stu;
# 例: select distinct class_id from stu;

The DISTINCT keyword only returns different values. If there are many a and many b values ​​in the column, only a and b are returned.

Insert picture description here

Limit the result LIMIT

select * from tbname limit 3,4;
# 代表从第三行开始检索,检索四行数据
# 代替的语法: limit 4 offset 3 意为从行3开始检索四行,和上面一样
# 例: select * from stu limit 3,4;

Insert picture description here

Use fully qualified table names

select name from stu;
select stu.name from stu;
select stu.name from demoDB.stu;

Sort the retrieved data ORDER BY


Sort data ORDER BY

select * from tbname order by 字段;

The data queried by default is not sorted randomly. If no sorting rule is specified, the data will generally be displayed in the order in which it appears in the underlying table

Relational database design theory believes that if the sort order is not clearly specified, it should not be assumed that the order of the retrieved data is meaningful

Usually, the column used in the ORDER BY clause will be the column selected for display.

But this is not necessarily the case, and it is completely legal to sort data with non-retrieved columns.

Sort by multiple columns

select * from tbname order by 字段1,字段2,...;

When multiple columns of data need to be sorted, separate the column names with commas, and the sort will be compared in order of the previous and the next, the default is ascending

select * from tbname order by 字段1(desc),字段2(desc),...;

Sort the specified column names in ascending or descending order, such as select * from stu order by class_id, age desc; first sort class_id in ascending order and then sort age in descending order

note

When the ORDER BY clause is given in the position of the ORDER BY clause, it should be ensured that it is located after the from clause.

If LIMIT is used, it must be located after the ORDER BY clause is completed. The wrong order of using clauses will result in an error message.

Data retrieval conditions filter WHERE


The database generally contains a large amount of data, and it is rarely necessary to retrieve all the rows in the table.

Usually only a subset of table data is extracted based on the needs of a specific operation or report.

To retrieve only the required data, you need to formulate search conditions

select 字段 from tbname where 条件; 

When using where and order by at the same time, where should be in the front and order by in the back

WHERE clause operator

Operator Description
= equal
<> 、!= not equal to
< Less than
<= less than or equal to
> more than the
>= greater than or equal to
BETWEEN … and … Specify between two values
IS NULL Null value

Combined WHERE clause

MySQL allows multiple WHERE clauses to be given.

Two ways: AND and OR connect the two clauses. Also called logical operator.

AND

AND is used in the WHERE clause to retrieve all the conditions that must be met and connected before returning. Otherwise return empty set

select 字段 from tbname where 字段=.. and 字段=..;
# 例:
select name from stu where age = 22 and sex = 'm';

OR

OR is used in the WHERE clause and is used to retrieve only one of the conditions of the or connection can be returned. Otherwise return empty set

AND and OR can be used together, but you must pay attention to the calculation order of SQL. SQL will give priority to AND operator before processing OR operator.

For example: Query female students in Class 1 and Class 2.

select * from stu where class_id=1 or class_id=2 and sex='女';

In this way, the following situation will occur
Insert picture description here

Because of the priority processing mechanism of AND, SQL thinks that it is the girls in class two and all the students in class one that need to be queried.

The solution is as follows:

select * from stu where class_id=1 and sex='女' or class_id=2 and sex='女';
# 或者
select * from stu where (class_id=1 or class_id=2) and sex='女';

Parentheses take precedence over and.

IN 和 NOT

IN

The IN operator is used to specify the range of conditions, and each condition in the range can be matched. Can be used in conjunction with AND and OR

select name from stu where class_id in (1,2) and sex='女';

Why use the IN operator? The advantages are as follows:

  • When using a long list of legal options, the syntax of the IN operator is clearer and more intuitive.
  • When using IN, the order of calculation is easier to understand (because there are fewer operators)
  • The IN operator is generally faster than the OR operator list
  • The biggest advantage of IN is that it can contain other SELECT statements, making it possible to create WHERE clauses more dynamically.

NOT

The NOT operator is used to specify all data except this condition.

select name from stu where class_id not in (1);

Use of wildcards

LIKE and wildcards

LIKE is suitable for fuzzy search, such as searching for all products that contain the text a in the product name.

  • Percent sign (%) wildcard in the search %to represent any characters appear any number of times.

    select name from stu where name like 'a%'; # 表示匹配第一个字符为a的所有数据
    select name from stu where name like '%a'; # 表示匹配最后一个字符为a的所有数据
    select name from stu where name like '%a%'; # 表示匹配包含字符a的所有数据
    
  • The underscore ( _) wildcard character, when using underscores, one underscore is equal to one character.

    select name from stu where name like '_a';# 表示匹配最后一个字符为a且总长度为两个字符的数据
    select name from stu where name like 'a_';# 表示第一个字符为a且总长度为两个字符的数据
    

Tips for using wildcards

  • Don't overuse wildcards. If other operators can achieve the same purpose, other operators should be used.
  • When you really need to use wildcards, don't put them at the beginning unless absolutely necessary, such as'%a'. Put the wildcard at the beginning, the search speed is the slowest.
  • Pay attention to the wildcard position.

Regular REGEXP

select name from stu where name regexp '[0-5]abc'; # 第一个字符为0-5,后面为abc的所有数据

Statistical functions (aggregate functions) in MySQL

Use of convergent functions

We often need to summarize data without actually retrieving them all. For this purpose, MySQL provides special functions.

Using these functions, MySQL queries can be used to retrieve specific data, analyze and form reports.

such as:

  • Determine the number of rows in the table
  • Get the sum of the columns in the table.
  • Find out the maximum, minimum, and average values ​​of table columns (or all rows, some specific rows).
function Description
COUNT() Returns the number of rows in a column
MAX() Returns the maximum value of a column
MIN () Returns the minimum value of a column
SUM() Returns the sum of a column value
AVG() Returns the average value of a column

note:

When using count, if the column name is specified, the row whose value is NULL is ignored, but if the asterisk (*) is used in the function, it is not ignored.

GROUP BY & HAVING

GROUP BY

SQL aggregate functions can be used to summarize data. This is where we can perform techniques on the rows, calculate the sum and average, and obtain the maximum and minimum values ​​without retrieving all the data.

So far, all calculations are performed on all data in the table or data matching a specific WHERE clause.

But then we can use group by...having to filter again after grouping.

For example: we need to get the number of students in all classes

mysql> select class_id,count(*) as nums from stu where class_id=1;
+----------+------+
| class_id | nums |
+----------+------+
|        1 |    6 |
+----------+------+
1 row in set (0.00 sec)

mysql> select class_id,count(*) as nums from stu where class_id=2;
+----------+------+
| class_id | nums |
+----------+------+
|        2 |    4 |
+----------+------+
1 row in set (0.00 sec)

We need to query twice.

But if we need to query the number of students in each class in a school, this method is obviously inappropriate. What should we do?

At this time, grouping is needed. SQL grouping allows data to be divided into multiple logical groups so that each group can be aggregated and calculated (group by).

Syntax: select field, function(*) as column name from tbname group by field;

mysql> select class_id,count(*) as nums from stu group by class_id;
+----------+------+
| class_id | nums |
+----------+------+
|        1 |    6 |
|        2 |    4 |
+----------+------+
2 rows in set (0.00 sec)

What if you want the system to return a class with less than 5 people or a class with more than 5 people?

It is necessary to filter again from the returned results above, which is the HAVING filter group below

HAVING

In addition to grouping data with GROUP BY, MySQL also allows filtering groups, including those groups, and exclude those groups.

For example, as mentioned above, let the system return a class with less than 5 people

In fact, all the WHERE clauses mentioned before can be replaced by HAVING. The only difference is that WHERE filters rows and HAVING filters groups .

Syntax: Syntax: select field, function(*) as column name from tbname group by field having condition;

# 大于五人的班级
mysql> select class_id,count(*) as nums from stu group by class_id having nums>5;
+----------+------+
| class_id | nums |
+----------+------+
|        1 |    6 |
+----------+------+
1 row in set (0.00 sec)

# 小于五人的班级
mysql> select class_id,count(*) as nums from stu group by class_id having nums<5;
+----------+------+
| class_id | nums |
+----------+------+
|        2 |    4 |
+----------+------+
1 row in set (0.00 sec)

Precautions

If you now need to add a field class_name to store the class name, filter class_id, class_name and the number of people

mysql> select class_id,count(*) as '数量' from stu group by class_id;
+----------+--------+
| class_id | 数量   |
+----------+--------+
|        1 |      6 |
|        2 |      4 |
+----------+--------+
2 rows in set (0.00 sec)

-- 在select里面有class_id、class_name,group by后面只有id就会出错

mysql> select class_id,class_name,count(*) as '数量' from stu group by class_id;
ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'yuge.stu.class_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

-- 正确的语句,应该是吧select所有列都作为分组条件。
mysql> select class_id,class_name,count(*) as '数量' from stu group by class_id,class_name;
+----------+------------+--------+
| class_id | class_name | 数量   |
+----------+------------+--------+
|        1 | c1         |      6 |
|        2 | c2         |      4 |
+----------+------------+--------+
2 rows in set (0.00 sec)

ncompatible with sql_mode=only_full_group_by

-The correct statement, it should be select all columns as grouping conditions.

mysql> select class_id,class_name,count(*) as '数量' from stu group by class_id,class_name;
+----------+------------+--------+
| class_id | class_name | 数量   |
+----------+------------+--------+
|        1 | c1         |      6 |
|        2 | c2         |      4 |
+----------+------------+--------+
2 rows in set (0.00 sec)

Guess you like

Origin blog.csdn.net/weixin_43701183/article/details/114117685