Introduction to two UNION query instances in MySQL

Source: Internet
Author: User

In mysql, UNION queries are combined with multi-table queries. Here we will give you a general introduction to the syntax usage and Performance Comparison of UNION queries, hoping to help you.

I. union query usage

The union query is relatively simple. It seems that the two tables are merged and the fields are also merged.

For example

Select * from table1, table2

The two identical fields are not merged,

Select a1 from table1 union select a1 from table2

In this way, the a1 of the two tables can be merged into one

I don't know what you see above. If we don't, let's continue to look at the instance.

1. Use the SELECT clause for multi-table queries

SELECT field name FROM table 1, Table 2... WHERE table 1. Field = TABLE 2. Field AND other query Conditions
SELECT. id,. name,. address,. date, B. math, B. english, B. chinese FROM tb_demo065_tel AS B, tb_demo065 AS a WHERE. id = B. id
Note: In the code above, two table associations are created based on the same id field information of the two tables, but they should not be used in actual development, it is best to use the primary and foreign key constraints for implementation.

 

2. Use the table alias for multi-Table query

For example, SELECT. id,. name,. address, B. math, B. english, B. chinese FROM tb_demo065 a, tb_demo065_tel B WHERE. id = B. id AND B. id = '$ _ POST [textid]'

In SQL, you can specify an alias for a table in two ways.
The first is specified by the keyword AS, such

SELECT a. id, a. name, a. address, B. math, B. english, B. chinese FROM tb_demo065 AS a, tb_demo065_tel AS B WHERE a. id = B. id

The second is to directly add the table alias after the table name.

SELECT a. id, a. name, a. address, B. math, B. english, B. chinese FROM tb_demo065 a, tb_demo065_tel B WHERE a. id = B. id

Note the following when using the table alias:

(1) An alias is usually a shortened table name used to reference a specific column in the table in the connection. If multiple tables in the connection have the same name column, the column name must be specified by the table name or table alias.
(2) If the table alias is defined, the table name cannot be used any more.

2. How is the union efficiency?


. Multi-Table connection type
1. cartesian products (cross join) can be considered as cross join in MySQL, or CROSS is omitted, or ',' such:


 
SELECT * FROM table1 cross join table2
SELECT * FROM table1 JOIN table2
SELECT * FROM table1, table2


Because the returned result is the product of the two connected data tables, we do not recommend this function when the WHERE, ON, or USING conditions exist, because when there are too many data table projects, it will be very slow. Generally, LEFT [OUTER] JOIN or RIGHT [OUTER] JOIN is used.

2. inner join: in MySQL, inner join is called an equijoin. That is, the equijoin conditions must be specified. In MySQL, CROSS and inner join are divided together. Join_table: table_reference [INNER | CROSS] JOIN table_factor [join_condition]

3. mySQL outer join is divided into left Outer Join and right join. In addition to returning results that meet the connection conditions, the left table (left join) or right table (right join) is also returned) results that do not meet the connection conditions, corresponding to the use of NULL.

Example:

User table:

Id | name
---
1 | libk
2 | zyfon
3 | daodao

User_action table:

User_id | action
-----
1 | jump
1 | kick
1 | jump
2 | run
4 | swim

SQL:


Select id, name, action from user as u
Left join user_action a on u. id = a. user_id


Result:
Id | name | action
-----------
1 | libk | jump ①
1 | libk | kick ②
1 | libk | jump ③
2 | zyfon | run ④
3 | daodao | null ⑤

Analysis:
Note that user_action has a user_id = 4, action = swim record, but it does not appear in the result,
In the user table, the id = 3 and name = daodao users do not have corresponding records in user_action, but they appear in the result set.
Because it is left join, all work is subject to left.
Result 1, 2, 3, 4 are records in both the left table and the right table. 5 is a record in only the left table, not in the right table.

 

Working principle:

Read one record from the left table and select all records (n records) in the right table that match on to Form n records (including duplicate rows, for example: result 1 and result 3). If there is no table matching the on condition on the right side, all connected fields are null. then read the next one.

Extended:
If there is no on matching in the right table, we can display the null rule to find all records in the left table, not in the right table. Note that the column to be judged must be declared as not null.
For example:
SQL:


Select id, name, action from user as u
Left join user_action a on u. id = a. user_id
Where a. user_id is NULL


(Note:

1. If the column value is null, it should be "is null" instead of "= NULL ".
2. Here the. user_id column must be declared as not null.

)
Result of the preceding SQL statement:
Id | name | action
---------
3 | daodao | NULL

---------------------------

General Usage:

A. LEFT [OUTER] JOIN:

In addition to returning results that meet the connection conditions, you must also display data columns that do not meet the connection conditions in the left table.

 

SELECT column_name FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.column


B. RIGHT [OUTER] JOIN:

The difference between RIGHT and left join is that in addition to displaying results that meet the connection conditions, you also need to display data columns that do not meet the connection conditions in the RIGHT table.

 

SELECT column_name FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column = table2.column

Tips:

1. on a. c1 = B. c1 is equivalent to using (c1)
2. inner join and (comma) are semantically equivalent.
3. When MySQL retrieves information from a table, you can prompt which index it chooses.
This feature is useful if the EXPLAIN command shows that MySQL uses an index that may be incorrect in the index list.
By specifying the use index (key_list), you can tell MySQL to USE the most appropriate INDEX to find record rows in the table.
The optional syntax ignore index (key_list) can be used to tell MySQL not to use a specific INDEX. For example:


Mysql> SELECT * FROM table1 use index (key1, key2)
-> WHERE key1 = 1 AND key2 = 2 AND key3 = 3;
Mysql> SELECT * FROM table1 ignore index (key3)
-> WHERE key1 = 1 AND key2 = 2 AND key3 = 3;

2. Constraints for table join
Add the WHERE, ON, and USING display conditions.

1. WHERE clause

Mysql>

 
SELECT * FROM table1, table2 WHERE table1.id = table2.id;
2. ON

Mysql>


SELECT * FROM table1 left join table2 ON table1.id = table2.id;

SELECT * FROM table1 left join table2 ON table1.id = table2.id
Left join table3 ON table2.id = table3.id;
3. USING clause. If the two columns of the join two tables have the same names, you can use USING

For example:

Select from left join using ()

 

Examples of connecting more than two tables:

Mysql>


SELECT artists. Artist, cds. title, genres. genre

FROM cds

Left join genres N cds. genreID = genres. genreID

Left join artists ON cds. artistID = artists. artistID;

 

Or mysql>

 
SELECT artists. Artist, cds. title, genres. genre

FROM cds

Left join genres ON cds. genreID = genres. genreID

Left join artists-> ON cds. artistID = artists. artistID

WHERE (genres. genre = 'pop ');

--------------------------------------------

In addition, you need to note that when MySQL involves multi-table queries, You need to determine which connection method is more efficient Based on the query conditions.

1. cross join (Cartesian Product) or inner join [INNER | CROSS] JOIN

2. left outer join left [OUTER] JOIN or right outer join right [OUTER] JOIN. Specify the connection conditions WHERE, ON, and USING.

3. How does MySQL optimize left join and right join?


In MySQL, the execution process of a left join B join_condition is as follows:

1) · set table B based on all tables on which table A and table A depend.

2). Set Table A according to all tables used in the left join condition (except B.

3) The left join condition is used to determine how to search rows from Table B. (In other words, do not use any conditions in the WHERE clause ).

4) · all standard joins can be optimized, except for tables read from all the tables it depends on. If a circular dependency occurs, MySQL prompts an error.

5) perform all standard WHERE optimizations.

6) If A has A row that matches the WHERE clause, but B does not have A row that matches the ON condition, another B row is generated, and all columns are set to NULL.

7). If left join is used to locate rows that do NOT exist in some tables and perform the following test: col_name is null in the WHERE section, WHERE col_name IS a column declared as not null, mySQL finds a row that matches the left join condition and stops searching for other rows (for a specific keyword combination.

The execution of right join is similar to that of left join, but the role of the table is the opposite.

The order in which the join optimizer calculates the table to be joined. The forced read sequence of left join and STRAIGHT_JOIN can help the JOIN optimizer to work faster, because fewer table exchanges are checked. Note that if the following type of query is executed, MySQL performs full scan B, because LEFT JOIN forces it to read before d:


SELECT *
FROM a, B LEFT JOIN c ON (c. key = a. key) LEFT JOIN d ON (d. key = a. key)
WHERE B. key = d. key;
In this case, the reverse order of a is used for restoration, and B is listed in the FROM clause:

 

SELECT *
FROM B, a LEFT JOIN c ON (c. key = a. key) LEFT JOIN d ON (d. key = a. key)
WHERE B. key = d. key;
MySQL can perform the following left join optimization: If the NULL row is generated, the WHERE condition is always false, and the left join is changed to a normal JOIN.

For example, in the following query, if t2.column1 is NULL, the WHERE clause is false:

 

SELECT * FROM t1 left join t2 ON (column1) WHERE t2.column2 = 5;

Therefore, you can safely convert a query to a normal join:


 
SELECT * FROM t1, t2 WHERE t2.column2 = 5 AND t1.column1 = t2.column1;

This is faster, because MySQL can use table T2. To force table order, use STRAIGHT_JOIN.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.