MYSQL notes 16-20

Create an advanced connection

Use table aliases

As mentioned earlier, aliases can be created with AS. In addition to being used for column names and calculated fields, SQL also allows aliasing of table names. There are two main reasons for this:

  • Shorten the SQL statement
  • It is allowed to use the same table multiple times in a single SELECT statement.
    Insert picture description hereThrough the above statement, you can see that all three tables in the FROM clause have aliases. Customers AS c establishes c as the alias for customers . In this example, the table alias is only Used in WHERE clauses, but table aliases can be used not only in WHERE clauses, but also in SELECT lists, ORDER BY clauses and other parts of the statement;

Use different types of connections

Previously, the simple connections used were internal connections or equivalent connections; there are three other types: self-connection, natural connection, and external connection;

Self-association

One of the main reasons for using table aliases is that the same table can be referenced more than once in a single SELECT statement;
Insert picture description herethis solution uses a subquery. The internal SELECT statement does a simple search and returns the vend_id with ID DTNTR. The ID is used in the WHERE clause of the external query to retrieve this data;

Insert picture description hereThis is the same query using joins. The two tables required by this query are actually the same table. Therefore, the products table appears twice in the FROM clause. This is legal, but the reference to products is ambiguous Yes, because MYSQL does not know that you are referring to the instance in the products table;
for this, I used two aliases, p1, p2, and connected the lookup table based on the instance, and filtered the data by the prod_id in the second table , Return the required data.
Self-join is usually used as an external statement to replace the subquery used when retrieving data from the same table. The final result is the same, but sometimes processing the connection is much faster than processing the subquery;

Natural connection

Whenever the table is joined, there should be at least one list. Now it should not only be in the table. The standard join returns all the data, and there will even be multiple occurrences. The natural join excludes multiple times, so that each column returns once; the
natural join Is such a join, in which you can only select those unique columns, this is generally done by using wildcards (SELECT *) for the table, and explicit subsets for all other table columns:
Insert picture description herein this example, the wildcard Only used for the first table, all other columns are clearly listed, so no duplicate columns are retrieved;

External connection

Many joins associate rows in one table with rows in another table, and sometimes need to include rows that have no associated rows; joins include rows that have no associated rows in the related table. This type is called external coupling
Insert picture description herethis SELECT statement uses oUTER jOIN to specify the type of coupling, but inside the associated coupling two different rows in the table is no external coupling line further includes associated row, when using oUTER jOIN syntax must be used LEFT or RIGHT The keyword specifies the table containing all rows (RIGHT refers to the table on the right of OUTER JOIN, and LEFT refers to the table on the left of OUTER JOIN)

Use joins with aggregate functions

Aggregate functions are used to aggregate data. All examples of aggregate functions are only aggregated from a single table. These functions can also be used with joins:
Insert picture description herethis SELECT statement uses INNER JOIN to associate the customers and Orders tables with each other, and the GROUP BY clause groups data by customers , The function calls COUT to count each data and returns as num_ord

Aggregate functions can also be easily used with other connections
Insert picture description here

Use connection and connection conditions

Key points of connection and its use:

  • Pay attention to the type of connection used, generally internal connection is used, but external connection is also effective
  • Ensure that the correct connection conditions are used, otherwise incorrect data will be returned
  • Connection conditions should always be provided, otherwise Cartesian product will be obtained
  • A connection can contain multiple tables, and even different connection types can be used for each connection. Although it is legal, it is generally useful, and each connection should be tested separately before use

Combined query

Combined query

mysql allows multiple queries, the query and the result set as a single return, these compositions commonly referred to as queries and (Union) or compound query (compound query)
There are two basic cases where it is desirable to use a combination of query:

  • Return similarly structured data from different tables in a single query
  • Perform multiple queries on a single table and return data according to a single query

Create a combined query

The UNION operator can be used to combine several SQL queries. With UNION, multiple SELECT statements can be given and their results can be combined into a single result set;

Use UNION

The use of UNION is very simple, given each SELECT statement, put the keyword UNION
Insert picture description hereInsert picture description herebetween the statements to combine the two statements, as follows:
Insert picture description hereThese statements are composed of the two previous SELECT statements, and the statements are separated by the UNION keyword. , UNION instructs Mysql to execute two SELECT statements and combine the output into a query result set;

UNION rules

Several rules in the use of UNION:

  1. UNION must be composed of two or more SELECT statements, separated by the keyword UNION between the statements (so, if you combine 4 SELECT statements, you need to use 3 UNION keywords)
  2. Each query in UNION must contain the same columns, expressions or aggregate functions (but the columns do not need to be listed in the same order)
  3. Column data types must be compatible: the types do not have to be exactly the same, but must be a conversion type that the DBMS can implicitly (for example, different numeric types or different date types).

Include or eliminate duplicate rows

When using UNION, duplicate rows are automatically cancelled. This is the default behavior of UNION. If necessary, you can change it. You can use UNION ALL instead of UNION.
Insert picture description hereUse UNION ALL, MYSQL does not cancel duplicate rows;

Sort combined query results

Insert picture description hereThe output of the SELECT statement is sorted by the ORDER BY clause. When using the UNION combination query, only one ORDER BY clause can be used. It must appear after the last SLECT statement. For the result set, there is no way to sort part of it, so it is not Multiple ORDER BY clauses are allowed;
although the ORDERY BY clause only appears later, it sorts the data of all SELECT statements;

Full text search

Understand full text search

Although there was the LIKE keyword before, it uses wildcard operators to match text. Using LIKE, you can find lines that contain special values ​​or partial values.
Although the search mechanism is very useful, there are several limitations:

  • Performance-wildcard and regular expression matching usually requires MYSQL to try to match all rows in the table. Therefore, due to the increasing number of rows being searched, these searches can be very time-consuming
  • Clear control-use wildcards and regular expression matching. It is difficult to clearly control what is matched and what is not matched;
  • Intelligent results-although searches based on wildcards and regular expressions provide very flexible searches, none of them provide an intelligent way to select results;
    all these restrictions and more restrictions can be used in full text Search to solve it. When using full-text search, mysql does not need to view each row separately, nor does it need to analyze and process each word separately. MySQL creates an index for each word in the specified column, and the search can search for these words;

Use full text search

For full-text search, the columns to be indexed need to be changed as the data changes. MySQL will automatically perform indexing and re-indexing;
after that, SELECT can be used with MATCH() and Against() to actually perform the search

Enable full text search support

When creating a table, enable full-text search. The CREATE TABLE statement accepts the FULLTEXT clause, which gives a comma-separated list of indexed columns;
Insert picture description hereCREATE TABLE: Creates a table; first look at the FULLTEXT clause, MYSQL according to the clause FULLTEXT ( note_text) for indexing, where FULLTEXT indexes a single column, or you can specify multiple columns;

Perform a full text search

Insert picture description hereAfter indexing, use two functions Match and Against to perform a full-text search, where Match specifies the column to be searched, and Against specifies the search expression to be used; //unless we use the BINARY method, the full-text search is not case-sensitive

Insert picture description hereThe above search can also use LIKE for full-text search, but the order is different;
Insert picture description hereMATCH and Against are used in the SELECT instead of the WHERE clause, which causes all rows to be returned. Match and against are used to create a calculated column, this column Contains the level value calculated by the full text search. The level is calculated and processed by MYSQL based on the number of words in the row, the number of unique words, and the entire index;

Use query expansion

Query expansion is used to try to relax the scope of the full-text search results returned. This is also a task of query expansion. When query expansion is used, MySQL performs two scans of data and indexes to complete the search:

  • First: Perform a basic full-text search to find all lines that match the search criteria'
  • Second, MySQL checks these matching rows and selects all useful words
  • After that, MySQL performed a full-text search again, this time using not only the original conditions, but also all useful words;
    Insert picture description here

Boolean text search

mysql supports another way of full text search: called Boolean mode (boolean mode), in Boolean mode.

  • Word to match
  • Words to exclude
  • Rank improvement
  • Expression grouping
  • In addition,
    Insert picture description herethis full-text search retrieves all lines containing the word heavy. The keyword IN BOOLEAN MODE is used. In fact, no Boolean operator is specified, so the result is the same as the one that is not specified;

Insert picture description here

Insert data

Data insertion

INSERT is used to insert rows into a database table. Insertion can be used in several ways:

  • Insert complete line
  • Insert part of the row
  • Insert multiple rows
  • Insert the results of certain queries

Insert complete line

The simplest way to insert data into a table is to use the INSERT syntax: the table name and the value to be inserted into the new row are required:

	INSERT INTO Customers
	VALUES(NULL,
		'Pep E.	LaPew',
		'100 Main Street',
		'Los Angeles',
		'CA',
		'90046'
		'USA'
		NULL,
		NULL);	

The INSERT statement generally does not produce output. This statement inserts a new customer into the customers table. The data stored in each table column is given in the VALUES clause. A value must be provided for each column. The above insert statement May not be safe enough;

INSERT INTO customers(cust_name,
	cust_address,
	cust_city,
	cust_state,
	cust_zipe,
	cust_country,
	cust_contact,
	cust_email)
	VALUES(NULL,
	'Pep E.	LaPew',
	'100 Main Street',
	'Los Angeles',
	'CA',
	'90046'
	'USA'
	NULL,
	NULL);	

Although the job is the same, it is a bit cumbersome; but it is safe enough;

Insert multiple columns

INSERT can insert a row into a table, what if you want to insert multiple rows?
You can use multiple INSERT statements, submit them at once, and end each statement with a semicolon

INSERT INTO customers(cust_name,
	cust_address,
	cust_city,
	cust_state,
	cust_zipe,
	cust_country,
	)
	VALUES(NULL,
	'Pep E.	LaPew',
	'100 Main Street',
	'Los Angeles',
	'CA',
	'90046'
	'USA');	
	INSERT INTO customers(cust_name,
	cust_address,
	cust_city,
	cust_state,
	cust_zipe,
	cust_country,
	)
	VALUES('M.martian',
	'42 Galaxy way',
	'New York',
	'NY',
	'11213',
	'USA');	

Insert the retrieved data

There is another form of INSERT, which can be used to insert the result of a SELECT statement into the table. This retrieves the so-called INSERT SELECT, which is composed of INSERT and SELECT statements;

	INSERT INTO customers(cust_id,
		cust_contact,
		cust_email,
		cuts_name,
		cust_address,
		cust_city,
		cust_state,
		cust_zip,
		cust_country)
	SELECT cust_id,
		cust_cpmtact
		cust_email,
		cuts_name,
		cust_address,
		cust_city,
		cust_state,
		cust_zip,
		cust_country)
		FROM custenw;	

Use INSERT SELECT to import data from custnew;

Update and delete data

update data

In order to update (modify) the data in the table, you can use the UPDATE statement

  • Specific row in the update table
  • Update all rows in the table
	UPDATE customers
	SET cust_email = '[email protected]'
	WHERE cust_id=10005;

The UPDATEE statement ends with the where statement, which row has the highest number MySQL updated to;

delete data

In order to delete data from a table, use the DELEATE statement, you can use DELETE
to delete specific rows
from the table in two ways , delete all rows from the table

	DELETE FROM customers,
	WHERE cust_id=10006;

Delete the data in the customers table, cust_id=10006;

Guess you like

Origin blog.csdn.net/qq_29498749/article/details/109783380