"MySQL must know will be" 15 ~ Chapter 18

Chapter XV - Chapter XVIII

Chapter XV

The table is to ensure that the design of dividing the information into a plurality of tables, one table for a class of data, the tables used by the certain value (i.e. cross correlation relationship Design)

For example, we can set up two tables, a storage vendor information, the other information storage products, vendors table contains information on all suppliers, each supplier per line, they are called the primary key that uniquely identifies, such as vendor ID, products table only stores product information, vendor ID is not stored in addition to other information providers, and therefore also called the primary key vendors of products foreign keys , two tables it is associated , by using the vendor ID to find the corresponding table supplied from the vendors information providers.

Foreign Key : a foreign key to a table, which contains the primary key of another table

advantage:

· Supplier information is not repeated, saving time and space

· If the supplier information changes, vendors can update only a single record in the table, data from related tables do not change

· Because no duplicate data, the data is obviously consistent, make data processing easier, relational database scalability far better than non-relational databases

Scalability : the ability to adapt to the ever-increasing workload without fail, well-designed database or application is called good scalability

In a SELECT statement association table, called the coupling, may be coupled using this syntax table returns a set of a plurality of output lines coupled to the correct association table at runtime

When using relational tables, insert only legitimate data in relational very important, if inserted into the possession of illegal vendor ID in the products table (that is, does not appear in vendorsd table) vendors to produce products, these products are inaccessible, because there is no association to a supplier

Creating links is very simple, provides for the linking of all the tables and how they relate to

SELECT vend_name, prod_name, prod_price
FROM vendors, products
WHERE vendors.vend_id = products.vend_id
ORDER BY vend_name, prod_name;

When join several tables in a SELECT statement, the corresponding relations are constructed in operation, the database itself does not indicate how to join a table, it is necessary WHERE clause, join two tables when you actually do is each row of the first table and second table each row pair, screened (i.e., the join condition) by the WHERE clause

Cartesian product : the results returned by the table relationships not coupled condition is the Cartesian product of the number of rows retrieved will be the number of rows in the first table multiplied by the number of rows in the second table, the Cartesian product coupling type is called cross coupling

SELECT vend_name, prod_name, prod_price
FROM vendors, products
ORDER BY vend_name, prod_name;

We want to ensure that all links have the WHERE clause

Coupling presently used for the equivalent links , based on equality test between the two tables, also known as the internal coupling , the coupling may be used for such a different manner, where the relationship between two tables specified using INNER JOIN

SELECT vend_name, prod_name, prod_price
FROM vendors INNER JOIN products
ON vendors.vend_id = products.vend_id;

Join multiple tables

SELECT prod_name, vend_name, prod_price, quantity
FROM orderitems, products, vendors
WHERE products.vend_id = vendors.vend_id
	AND orderitems.prod_id = products.prod_id
	AND order_num = 20005;

This example shows the number of items in the order of 20005, the table to find the products table items according to corresponding row prod_id order_num = 20005, and in the corresponding company to vendors to find the corresponding vend_id

The more linked tables, the more severe performance degradation

Recalling the subquery before Chapter 14

SELECT cust_name, cust_contact
FROM customers
WHERE cust_id IN (SELECT cust_id
                  FROM orderts
                  WHERE order_num IN (SELECT order_num
                                      FROM order_items
                                      WHERE prod_id = 'TNT2'));

You can use links

SELECT cust_name, cust_contact
FROM customers, orders, orderitems
WHERE customers.cust_id = orders.cust_id
	AND orderitems.order_num = orders.order_num
	AND prod_id = 'TNT2';

WHERE clause two associated front and rear a filter

Chapter XVI

In addition to the column name aliases, calculated field (similar to the columns) outside. SQL also allows to the table name from the alias to shorten the SQL statement, as a convenience to repeated use of the table name

SELECT cust_name, cust_contact
FROM customers AS c, orders AS o, orderitems AS oi
WHERE c.cust_id = o.cust_id
	AND oi.order_num = o.order_num
	AND prod_id = 'TNT2';

Table alias not only used in the WHERE clause can also be used in the SELECT list, ORDER BY clause, as well as other parts, but only to pay attention to the table alias in query execution, not returned to the client

Before you use only internal links or the equivalent link, then introduce other links

Self-join, if you find an article (ID is DTNTR) problems, and would like to know what other items the commodity suppliers have no problem, so to find all the items that a vendor can use subqueries

SELECT prod_id, prod_name
FROM products
WHERE vend_id = (SELECT vend_id
                FROM products
                WHERE prod_id = 'DTNTR');

Use link

SELECT p1.prod_id, p1.prod_name
FROM products AS p1, products AS p2
WHERE p1.vend_id = p2.vend_id
	AND p2.prod_id = 'DTNTR';

This query is actually two tables in the same table, but with ambiguous references to the products table. MySQL does not know which instance is referenced products, so with p1, p2 distinction

When the table is linked with one or more of the listed now more than one table, so the standard coupling may return duplicate column, natural links can exclude this case at least, each column returned only once, but we need to yourself

SELECT c.*, o.order_num, o.order_date,
	   oi.prod_id, oi.quantity, oi.item_price
FROM customers ASc, orders AS o, orderitems AS oi
WHERE c.cust_id = o.cust_id
	AND oi.order_num = o.order_num
	AND prod_id = 'FB';

For a table using a wildcard, all the other columns explicitly listed, it will not be repeated, in fact, we probably never use internal links are not naturally coupled

External links do not contain those lines associated with rows in a related table

First use the inner join to retrieve all customers orders

SELECT customers.cust_id, orders.order_num
FROM customers INNER JOIN orders
  ON customers.cust_id = orders.cust_id;

External links retrieve all customers

SELECT customers.cust_id, orders.order_num
FROM customers LEFT OUTER JOIN orders
  ON customers.cust_id = orders.cust_id;

Further comprising external coupling line not associated rows, in use OUTER JOIN, LEFT or RIGHT key must be used to specify the table including all the rows, using the above example LEFT OUTER JOIN from customers of all rows, to select the right All rows in the table (Orders) in, using RIGHT OUTER jOIN, the following example (ON clause interchangeable position on both sides of the equal sign, only a join condition)

SELECT customers.cust_id, orders.order_num
FROM customers RIGHT OUTER JOIN orders
  ON orders.cust_id = customers.cust_id;

Aggregation function may be used together with the links, such as the number of orders to retrieve all of the customers at each customer and may be used COUNT () function, a packet data by customer

SELECT customers.cust_name,
	   customers.cust_id,
	   COUNT(orders.order_num) AS num_ord
FROM customers INNER JOIN orders
ON customers.cust_id = orders.cust_id
GROUP BY customers.cust_id;

Can also be used with external links, no customer orders will be displayed

SELECT customers.cust_name,
	   customers.cust_id,
	   COUNT(orders.order_num) AS num_ord
FROM customers LEFT OUTER JOIN orders
ON customers.cust_id = orders.cust_id
GROUP BY customers.cust_id;

Coupling and coupling conditions of use

* Note coupling type, generally use internal links, external links but also effective

· Use the correct join condition, and must have the join condition, otherwise they will get the Cartesian product

Chapter XVII

MySQL allows multiple queries (multiple SELECT statements), as a result of a single query and returns a result set, and these compositions or queries are usually referred to as compound query

There are two basic situations require the use of a combination of query:

· Returning data from a similar structure different tables in a single query

· Execute multiple queries on a single table, by a single query to return data

Any SELECT statement with multiple WHERE clause can be given as a combination of query

UNION operator to combine the available number of SQL queries, the results of the combination thereof into a single result set

SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
UNION
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001, 1002);

Here you can also use multiple WHERE clause to accomplish the same task

SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
   OR vend_id IN (1001, 1002);

For the more complex filters or retrieve data from multiple tables, it may be easier to use UNION

UNION rule

· UNION must consist of more than two or two SELECT statements

· The UNION each query must contain the same column, expression, or aggregate functions (but does not require the individual columns listed in the same order)

· Column data types must be compatible, do not have exactly the same type, but must be DBMS types (e.g., different types or different values of a date type) may be converted implicitly

UNION the query results automatically removes duplicate rows, this is the default behavior UNION, but it also can change, you can use UNION ALL

SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
UNION ALL
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001, 1002);

UNION ALL WHERE can not complete the work done, if you really need all rows (including duplicates) appears, you must use UNION ALL instead of WHERE

Combination of query results can be sorted, but only a ORDER BY clause and must appear after the final SELECT statement, MySQL use it to sort all the results of all the SELECT statement returns

SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5
UNION 
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001, 1002)
ORDER BY vend_id, prod_price;

Using a combination of UNION query not just for a table can be applied to different tables

Chapter XVIII

MyISAM and InnoDB support full-text search is not supported

Use LIKE keyword or regular expression matching required MySQL table all the rows, with the increase in the number of lines, it can be time consuming and not easy to define what matches do not match, such as specifying a word must match a word and must not match results were not intelligent, as it does not distinguish a plurality of rows and rows that match a single match (match line the same row multiple times)

These problems can be solved with a full-text search, MySQL does not need at this time to see each line separately, you do not need to analyze and process each word separately

For full-text search, index column must be searched, when the CREATE TABLE, MySQL index for the column according to the instructions clause FULLTEXT (note_text), if necessary can also specify multiple columns, you can specify when you create the table FULLTEXT or later, do not use FULLTEXT when importing data

After the index, use the function Match (), Against (), Match () specifies a search column, Against () to specify search expressions to be used

SELECT note_text
FROM productnotes
WHERE Match(note_text) Against('rabbit');

If the changed 'rabbi', there is no result

Values ​​to Match () must () is defined in the same FULLTEXT, specify multiple, and they must be listed in the right order, unless BINARY mode, or is not case sensitive

Just search can also be used to complete the LIKE clause

SELECT note_text
FROM productnotes
WHERE note_text LIKE '%rabbit%'

Do not use the ORDER BY clause and returns two results but full text of this sort with a good degree of match, with high levels of rows returned first

SELECT note_text,
	   Match(note_text) Against('rabbit') AS rank1
FROM productnotes;

In the new version of MySQL in rank as a reserved word, so instead rank1

SELECT functions using two rather than all rows are returned WHERE, rank1 each row represents a column full-text search of the calculated level values

The level number of word lines, the number of unique words like manner calculated from MySQL, does not include 'rabbit' line level is 0, so if using a WHERE clause is excluded level 0 and level values ​​in descending order according to

If you specify multiple search terms, include more higher-level matches the number of word lines

Queries can be used to extend the range of the relaxation of the search results, that the bank did not specify the word, but the search for

SELECT note_text
FROM productnotes
WHERE Match(note_text) 
	  Against('anvils' WITH QUERY EXPANSION);

Through the data and indexes two passes to complete the search

To be a substantially full-text search to find all the rows that match the criteria described above, the embodiment shown a search and check the matching lines and MySQL selecting these word lines are useful (e.g., customer and Recommend), plus these useful words then walk in a full-text search results that contain the word anvils foremost

Boolean text search to match the specified word, the word to be excluded (even if the line contains the specified word does not return), arrange prompt (to specify certain words are more important than other words rating higher), and even if not defined FULLTEXT index, It may also be used, but is relatively slow

To match all lines but does not contain any word beginning with rope, you can use the following query

SELECT note_text
FROM productnotes
WHERE Match(note_text) 
	  Against('heavy -rope*' IN BOOLEAN MODE);

The following table shows the use of Boolean operators as well as some

Boolean operators Explanation
+ Contains word must be present
- Exclusion, the word must not appear
> It contains, and increasing the level of value
< Comprising, and reduced level value
( ) The sub-word expressions (expressions allow these is contained as a sub-group, and the like excluded)
~ Cancel a word ranking value
* Suffix wildcard
" " The definition of a phrase, include or exclude

For example:

Matching the line containing the word rabbit and bait

SELECT note_text
FROM productnotes
WHERE Match(note_text)
	  Against('+rabbit +bait' IN BOOLEAN MODE);

Operator is not specified, and a matching rabbit bait comprising at least one word line

SELECT note_text
FROM productnotes
WHERE Match(note_text)
	  Agaisnt('rabbit bait' IN BOOLEAN MODE);

Matching phrase rabbit bait rather than the two words are matched

SELECT note_text
FROM productnotes
WHERE Match(note_text)
	  Against('"rabbit bait"' IN BOOLEAN MODE);

A second election, increasing the former level, which level reduction

SELECT note_text
FROM productnotes
WHERE Match(note_text)
	  Against('>rabbit <carrot' IN BOOLEAN MODE);

Match two words, reducing the latter's rating

SELECT note_text
FROM productnotes
WHERE Match(note_text) 
	  Against('+safe +(<combination)' IN BOOLEAN MODE);

Without sorting arrangement: Boolean line mode, not according to the level value returned in descending order

Notes on full-text search

· When indexing full-text data, short words are ignored and excluded from the index, the short term is defined as the word that is three characters or less

· MySQL has a non-built-in word list, the words are always ignored when indexing full-text data, there is a need to cover

· If a word appears in more than 50% of the rows, it will be ignored as a non-word, this rule does not apply IN BOOLEAN MODE

* Table number of rows <= 2 line, full-text search does not return a result, as a rule 50%

· Ignore single quotes such as do not dont index

Published 84 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43569916/article/details/104375793