MySQL Higher Order Statements and Views

Table of contents

1. Common queries

1. Sort by Keyword

2. Interval judgment and query are not repeated records

3. Group the results

4. Limit result entries (limit)

5. Set aliases (alias→as)

6. Wildcards

7. Subqueries

2. MySQL view


1. Common queries

(Add, delete, modify, check)

       In addition to the basic query, the query to the MySQL database sometimes needs to process the result set of the query. For example, fetching only a few pieces of data, sorting or grouping query results, etc.

1. Sort by Keyword

Similar to the windows task manager, you can
       use the SELECT statement to query the required data from the MySQL database. If you sort the results of the query, you can use the ORDER BY statement to sort the statements, and finally return the sorted results to the user. . This statement can sort not only for one field, but also for multiple fields.

grammar

select column1, column2, ... FROM table_name order by colunn1, column2, ...

ON|OFF;
       

        ASC is sorted in ascending order, which is the default sorting method, that is, ASC can be omitted. If no specific sorting method is specified in the select statement, the default sorting method is ASC.
       DESC is sorted in descending order. Of course, you can also use the where clause to further filter the query results before order by.

例:

数据库有一张表,记录了id,姓名,分数,地址和爱好

create table 表名 (id int, name varchar(10) primary key not null,score decimal(5,2),address varchar (20), hobbid int(5));

insert into info values(1,'liuyi',80, 'beijing',2);
insert into info values (2,'wangwu',90,'shengzheng',2);
insert into info values(3,'lisi',60,'shanghai',4);
insert into info values(4,'tianqi',99,'hangzhou',5);
insert into info values(5,'j iaoshou',98,'laowo',3);
insert into info values (6,'hanmeimei',10,'nanjing,3);
insert into info values(7,'lilei',11,'nanjing',5);

select * from 表名;

  

 

  

Sort by score, the default is to sort in ascending order

select id, name, score from 表名 order by score;

 

Scores in descending order

select id, name, score from 表名 order by score desc;

  

  

   

order by can also be combined with where for conditional filtering, and the students who filter a certain address are sorted in descending order by score

select name, score from 表名 where address-'address' order by score desc;

 

The order by
        statement can also use multiple fields for sorting. When there are multiple records with the same field as the first sorted field, these multiple records are sorted according to the second field, and the order by is followed by more records. When there are multiple fields, use English commas to separate the fields, and the priority is determined by the order.
        But the first parameter after order by is meaningful only when the same value appears.
① To query student information, first sort it in descending order by interest id. For the same score, id is also sorted in descending order.

select id, name, hobbid from 表名 order by hobbid desc, id desc;

② To query student information, first sort it in descending order by interest id, and if the scores are the same, id is sorted in ascending order

select id, name, hobbid from 表名 order by hobbid desc, id;

 

 

 2. Interval judgment and query are not repeated records

①and/or
 

select * from 表名 where score >80 and score <=99;
select * from 表名 where score >80 or score <=99;

Nested/Multiple Conditions

select * from 表名 where score >80 or (score >85 and score <99);

Add:
②distinct query does not repeat records
Syntax:
 

select distinct 字段 from 表名;
select distinct hobbid from 表名;

 

 

 

 

 

 3. Group the results

       The results obtained through the SQL query can also be grouped by using the group by statement. Group by
is usually used in conjunction with aggregate functions. Commonly used aggregate functions include: count (COUNT), sum (SUM), When calculating the average (AVG), maximum value (MAX), minimum value (MIN), and group by, the results can be grouped by one or more fields.

(1) Grammar  

select column_name, aggregate_function (column_name) from table_name where column_name operator value group by column_name;

Group by the same hobbid, calculate the number of students with the same score (count based on the number of names)

select count (name),hobby from 表名 group by hobby; 

Combined with the where statement, filter groups with scores greater than or equal to 80, and count the number of students

select count (name) ,hobby from 表名 where score>=80 group by hobby;

Combine the order by to sort the calculated number of students in ascending order

select count (name) , score,hobby from 表名 where score>=80 group by hobby order by count (name) asc;

 

 

 4. Limit result entries (limit)

When using the MySQL SELECT statement to query the result records of limit limit output
       , the result set returns all matching records (rows). Sometimes only the first row or the first few rows need to be returned, in which case the limit clause needs to be used.

(1)语法
select column1, column2, ... from table_name limit [offset, ] number

The first parameter of limit is the position offset (optional parameter), which is to set which line MySQL starts to display.
If the first parameter is not set, the display will start from the first record in the table. It should be noted that the position offset of the first record is 0, the second is 1, and so on. The second parameter is to set the maximum number of rows returned.

Query all information to display the first 4 rows of records

select * from 表名 limit 3;

Start from line 4 and display 3 lines of content

select * from 表名 limit 3,3;

Combined with the order by statement, the first three rows are displayed in ascending order according to the size of the id

select id,name from 表名 order by id limit 3.

output the last three lines

select id, name from 表名 order by id desc limit 3;
select * from 表名 order by 主键字段 desc limit ;

 

 

 

 5. Set aliases (alias→as)

       

       When querying in MySQL, when the name of the table is long or some fields in the table are long, in order to facilitate writing or use the same table multiple times, you can set an alias for the field column or table. When using, use aliases directly, which is concise and clear, and enhances readability.

Syntax
aliases for columns

select column_name as alias_name from table_name; 

alias for table

select column_name(s) from table_name as alias_name;

       After using as, you can use alias_name instead of table_name, where the as statement is optional. The alias after as is mainly to provide a temporary name for the column or table in the table. It is used in the query process, and the actual table name or field name in the library will not be changed.

Example of column alias setting:

select name as 姓名,score as成绩 from info;

If the length of the table is relatively long, you can use as to set an alias for the table, and use the alias directly in the query process.

Temporarily set the alias of the data table as i
select name as name, score as result from table name as i;

Query the number of fields in the data table, displayed as number

select count (*) as number from 表名;

You can also display it without as

select count(*) number from 表名;

Usage scenarios:
(1) When querying complex tables, aliases can shorten the length of query statements.
(2) When multiple tables are connected to query (easy to understand, shorten the sql statement)

In addition, as can also be used as an operator for concatenating statements.
Create the t1 table and insert all the query records of the data table into the t1 table

create table test1 like info;
create table t1 as select * from 表名;
select * from t1;

Here the role of as:

(1) Create a new table t1 and define the table structure, insert the table data (same as the info table)
(2) But the "constraint" is not completely "copied" over # but if the original table is set with a primary key, then the attached table's : The default field will be set to a 0 by default.
Similar:
clone, copy table structure

create table t1 (select * from 表名) ;

You can also add a where statement to judge

create table test1 as select * from 表名 where score >=60;

When setting an alias for a table, make sure that the alias does not conflict with the names of other tables in the database.
Column aliases are displayed in the results, while table aliases are not displayed in the results and are only used when executing the query.

 

 

 

 

 6. Wildcards

Wildcards are mainly used to replace some characters in a string, and query related results by matching some characters.
        Usually wildcards are used together with like, and cooperate with the WHERE clause to complete the query task. There are two commonly used wildcards, namely:
%: The percent sign indicates zero, one or more characters. * (wildcard)
_ : Underscore represents a single character. . (single character)

Query records whose names start with c

select id, name from 表名 where name like 'c%' ;

Query records with a character between c and i in the name

select id,name from 表名 where name like 'c_ic_i';

Query records with g in the middle of the name

select id, name from 表名 where name like '%g%' ;

Query the name record with 3 characters after the specified content

select id, name from 表名 where name like '指定内容__';

Wildcards "%" and " " can be used not only alone, but also in combination to
query records whose names begin with s

select id, name from 表名 where name like 's%_';

 

 

 7. Subqueries

       

        A subquery, also known as an inner query or nested query, refers to a query statement nested within another query statement. The sub-query statement is executed before the main query statement, and the result is returned to the main query as an outer condition for further query filtering.
PS: The sub-statement can be the same as the table queried by the main statement, or it can be a different table.

Example of the same table:

select name, score from 表名 where id in (select id from 表名 where score >80);

The above main statement

select name,score from info where id 

Substatements (collections):

select id from info where score >80;

PS: The sq1 statement in the sub-statement is for, and finally filter out - a result set for the judgment condition of the main statement
in: the syntax for associating/connecting the main table and the sub-table

Different table/multi-table example: 

create table 表名 (id int); 
insert into 表名 values(1),(2),(3);

Multi-table query

select id,name,score from 表名 where id in (select * from 表名);

       Subqueries can be used not only in select statements, but also in insert, update, and delete. When nesting, a new subquery can be nested again inside the subquery, that is to say, it can be nested in multiple layers.

The syntax
in is used to determine whether a value is in a given result set, usually used in conjunction with subqueries

Syntax:
<expression> [not] in <subquery>
        Returns true when the expression is equal to a value in the result set returned by the subquery, otherwise returns false. If the not keyword is enabled, the return value is the opposite. It should be noted that subqueries can only return one column of data. If the requirements are complex and one column cannot solve the problem, you can use multi-level nesting to deal with it. In most cases, subqueries are used with select statements.

Query records with scores greater than 80

select name,score from 表名 where id in (select id from 表名 where score>80);

Subqueries can also be used in insert statements. The result set of the subquery can be inserted into other tables through the insert statement
, all the records in t1 are deleted, and the records in the data table are re-inserted.

insert into t1 select * from 表名 where id in (select id from 表名) ;
select * from t1;

The update statement can also use subqueries. The subquery in the update can be a single column or multiple columns when the set updates the content.

Change the score to 50

update info set score=50 where id in (select * from 表名 where id=2);
select * from info;
update info set score=100 where id not in (select * from 表名 where id >1);

Indicates that the result set (2, 3) that matches the id field in the data table is first matched,
and then the main statement is executed, and the where condition judgment/filtering is performed based on the id of the main statement

delete also works with subqueries

Delete records with scores greater than 80

delete from 表名 where id in (select id where score>80);
select id, name, score from t1;

You can also add not in front of in, which is the opposite of in, indicating negation (that is, not in the result set of the subquery)
to delete records whose scores are not greater than or equal to 80

delete from t1 where id not in (select id where score>=80);
select id,name,score from t1;

       The exists keyword is mainly used to determine whether the result set of the subquery is empty in the subquery. Returns true if not empty; otherwise, returns false.
       Query if there is a record with a score equal to 80, calculate the number of fields of info

select count(*) from 表名 where exists(select id from 表名 where score=80);

Personnel information statistics, only after everyone has signed in and the personnel information statistics table entry is completed, the statistics need to be performed)
Query If there are records with a score less than 50, the number of fields in info will be calculated. There is no information in the info table less than 50, so return 0

select count(*) from 表名 where exists (select id from 表名 where score<50);

Subquery, alias as
query data table id, name field

select id, name from 表名;

The above command can view the content of the data table.
When querying the result set as a table, you also need to use an alias. Example:
From the content of the id and name fields in the data table as the "content" output id part

select id from (select id,name from 表名);

At this time, an error will be reported, the reason is: .

select * from 表名

This is a standard format, and in the above query statement, the location of "table name" is actually a complete result set, which mysql cannot directly recognize, and at this time, an alias is set for the result set, with "select a.id from a" The query method treats this result set as a "table", and the data can be queried normally, as follows:

select a.id from (select id,name from 表名) a

equivalent to

select info.id, name from 表名;
select 表.字段,字段 from 表:

 

 

 

 

 

 

 

 

 2. MySQL view

View: Optimized Operation + Security Solution
A virtual table in the database. This virtual table does not contain real data, but only maps real data.
The view can be understood as a mirror / reflection, and the result set (data) is dynamically saved.

Base data table
(record) → map (projection) -- view

The role scenario [Figure]
provides "tables" of different result sets (displayed in the form of tables) for different people (authority identities).

Scope:

select * from info;        展示的部分是info表
select * from view_name;   展示的一张或多张表

Functions:
(1) Simplified query result set, flexible query, can present different result sets for different users, relatively higher security
(2) In essence, view is a kind of select (result set presentation).

PS: View is suitable for multi-table connection browsing! It is not suitable for adding, deleting, and changing,
while stored procedures are suitable for frequently used SQL statements, which can improve execution efficiency.

Differences and connections between views and tables
Differences:
(1) A view is a compiled SQL statement. Tables are not.
(2) The view has no actual physical record. And the table has.

show table status\G

(3) The table only uses the physical space and the view does not occupy the physical space. The view is only the existence of the logical concept. The table can modify it in time, but the view can only be modified by the created statement.
(4) View is a way to view the data table. It can query the data composed of some fields in the data table, which is just a collection of some SQL statements. From a security point of view, the view can not give the user access to the data table, and thus does not know the table structure.
(5) The table belongs to the table in the global schema and is a real table: the view belongs to the table of the local schema and is a virtual table.
(6) The creation and deletion of views only affect the view itself and the corresponding basic table. (But updating the view data will affect the base table).

Contact:
(1) A view is a table built on top of the basic table. Its structure (that is, the defined columns) and content (that is, all data rows) come from the basic table, and it exists according to the existence of the basic table. A view can correspond to one basic table, or it can correspond to multiple basic tables. A view is an abstraction of the base table and new relationships established in a logical sense.

Example:
A score of 80 is displayed in the view.
PS: This result will change dynamically, and at the same time, different views can be displayed to different groups of people (such as the scope of authority).

Create a view (single table)

create view v_score as select * from 表名 where score>=80;

View table status

show table status\G

View view

select * from v_score;

View view and source table structure

desc v_score;
desc info;

Create a view with multiple tables

Create test01 table

create table test01 (id int, name varchar(10) ,age char(10)) ;
insert into test01 values(1, ' zhangsan',20) ;
insert into test01 values(2, 'lisi',30) ;
insert into test01 values (3, 'wangwu',29) ;

Create a view that needs to output id, name, score and age

create view v_表名(id, name, score,age) as select 表名.id, 表名.name, 表名.score, test01.age from 表名, test01 where 表名.name-test01.name;
select * from v_info;

Modify the original table data

update 表名 set score='60' where name='liuyi';

View view

select * from v_score;

select * from 表名;

Modifying the table cannot modify the fields calculated by functions and composite functions.
Convenient query and security.
Convenient query: the indexing speed is fast, and multiple tables can be queried more quickly at the same time (the view does not save real data, and the view is essentially similar to select).
Security: The account we log in is root → has permissions, and the view cannot display complete constraints.

NULL value
        In the process of using SQL statements, the characters NULL are often encountered. Usually NULL is used to represent missing values, that is, the field has no value in the table. You can use NOT NULL if you restrict some fields from being empty when you create a table.
keywords

        If not used, it can be empty by default. When inserting a record or updating a record into the table, if the field does not have NOT NULL and has no value, the field of the new record will be saved as NULL. It should be noted that a NULL value is different from a field with a number 0 or blanks, and a field with a value of NULL has no value. In the SQL statement, IS NULL can be used to judge whether a field in the table is a NULL value, on the contrary, IS NOT NULL can be used to judge that it is not a NULL value.

When querying the data table structure, the name field does not allow null values.
The difference between a null value and a null value (air and vacuum).
A null value has a length of 0 and does not take up space, and a NULL value has a length of null and takes up space.
is null can not determine the null value.
Null values ​​are handled with "=" or "<>" (!=).

When count() calculates, NULL will be ignored, and null values ​​will be added to the calculation.

desc table name;
insert a record, enter null in the score field, and it is displayed as null.


verify:

alter table 表名 add column addr varchar(50);

update info set addr-'nj' where score >=70;

Statistics: Check if null will be added to the statistics.

update info set addr='nj' where score >=70;

Statistics: Check if null will be added to the statistics.

select count (addr) from info;

Modify one of the data in the info table to a null value''

update info set addr=''where name-'wangwu';

Number of statistics, check if null values ​​will not be added to the statistics

select count (addr) from info;

query null value

select * from 表名 where addr is NULL;

Query for non-null values
 

select * from 表名 where addr is not null;

 

 

 

 

 

 

 

 

 

 

  

  

 

 

 

 

View has no data, storage engine, just a kind of mapping 

 

Guess you like

Origin blog.csdn.net/Drw_Dcm/article/details/126938293