Introduction to two table union queries in MySQL

Source: Internet
Author: User
Tags aliases joins one table

One, union query usage

The union query is simpler, as if the two tables were merged and the fields were combined

If it is

SELECT * FROM table1, table2

Words, two of the same fields will not be merged but

Select A1 from table1 Union Select A1 from Table2

In this way, we can synthesize the A1 of the two tables into a

I don't know if you see it, no, let's see the example.

A multiple table query using the SELECT clause

SELECT field name from Table 1, table 2 ... WHERE table 1. field = Table 2. field and other query criteria
SELECT A.id,a.name,a.address,a.date,b.math,b.english,b.chinese from Tb_demo065_tel as b,tb_demo065 as a WHERE a.id=b.id
Note: In the above code, the ID field information of two table is the same as the condition to establish two table association, but in the actual development should not be used in this way, it is best to use the main foreign key constraints to implement

Using table aliases for multiple table queries

For example: 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 and b.id= ' $_post[textid] '

In the SQL language, you can specify aliases for tables in two ways
The first type is specified by the keyword as

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 the alias implementation that adds the table directly 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

Use the alias of a table to notice several points

(1) An alias is usually a shortened table name used to refer to a particular column in the table in a connection, and if the same name column exists in more than one table in the connection, the column name must be qualified with the table name or the alias of the table
(2) If you define a table alias, you can no longer use the table name

Two, what about union efficiency?


. Multiple Table connection types
1. Cartesian product (cross connection) in MySQL can be cross join or omit cross that join, or use ', ' such as:



SELECT * FROM table1 CROSS JOIN table2
SELECT * FROM table1 JOIN table2
SELECT * from Table1,table2


Because the result it returns is the product of the two data tables that are connected, it is generally not recommended when there is a where, on, or using conditions, because it is very slow when there are too many datasheet items. Generally use left [OUTER] Join or right [OUTER] Join

2. The INNER join INNER join inner join in MySQL is called equivalent connection, that is, you need to specify the equivalent join condition in MySQL cross and inner join are divided together. join_table:table_reference [INNER | CROSS] JOIN table_factor [join_condition]

3. The external connection in MySQL is divided into left outer and right connections, that is, in addition to returning the results of the join conditions, return to the left table (left) or the right table (right connection) does not conform to the conditions of the connection, the corresponding use of NULL correspondence.

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 there is also a user_id=4, Action=swim record in the user_action, but not in the results,
Id=3 in the user table, Name=daodao users do not have a corresponding record in user_action, but they appear in the result set
Because now is the left join, all work is left.
Results 1,2,3,4 are both in the left table and on the right table record, 5 is only on the left table, not on the right table record

Working principle:

Read one from the left table and select all the right table records (n bars) to match on. Forms N Records (including duplicate rows, such as: result 1 and result 3), and if the right side does not have a table matching the on condition, the connected field is null. Then continue reading the next one.

Extended:
We can use the right table without on match to show the law of NULL, to find all the records in the left table, not the right table, note that the column to be judged must be declared not NULL.
Such as:
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


Attention

1. A column value of NULL should be null and cannot be used with =null
2. Here the a.user_id column must be declared to not NULL.


Result of SQL above:
ID | name | Action
————————–
3 | Daodao | Null

——————————————————————————–

General usage:

A. Left [OUTER] JOIN:

In addition to returning results that match the join condition, you need to display data columns in the left table that do not meet the join criteria, and should use a null corresponding

SELECT column_name from table1 left [OUTER] JOIN table2 on Table1.column=table2.column


B. Right [OUTER] JOIN:

Right is different from the left join simply by displaying data columns that do not conform to the join condition in the right-hand table in addition to the results that match the join condition, using the null corresponding

SELECT column_name from table1 right [OUTER] JOIN table2 on Table1.column=table2.column

Tips:

1. On a.c1 = B.C1 equivalent to using (C1)
2. INNER JOIN and, (comma) are semantically equivalent
3. When MySQL retrieves information from a table, you can indicate which index it chooses.
This feature is useful if EXPLAIN shows that MySQL uses the wrong index in the list of possible indexes.
By specifying use index (key_list), you can tell MySQL to find a record row in a table using the most appropriate index in a possible index.
An optional two-choice syntax IGNORE index (key_list) can be used to tell MySQL not to use a specific index. Such as:


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 on table joins
Add display criteria where, ON, USING

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 a connected two table join condition have the same name, you can use the using

For example:

SELECT from left JOIN USING ()

Example of a connection with 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 ');

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

Also need to pay attention to the place in MySQL involved in multiple table query, need to query according to the situation, want to use which connection way more efficient.

1. Cross-linking (cartesian product) or inner join [INNER | CROSS] JOIN

2. Left outer join or right [OUTER] Join note Specifies the join condition where, on,using, the OUTER.

3. How MySQL optimizes left join and right join


In MySQL, A left JOIN B join_condition is executed as follows:

1) · Set Table B based on all tables that are dependent on tables A and a.

2) · Set Table A for all tables (except B) that are used in the left join condition.

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

4) · All standard joins can be optimized, except for tables that are read from all tables on which it relies. If there is a circular dependency, MySQL prompts for an error.

5) · Perform all standard where optimizations.

6) · If a row in a matches a WHERE clause, but no row in B matches the on condition, then another B row is generated, where all the columns are set to NULL.

7) · If you use a LEFT join to find a row that does not exist in some tables, and the following test: the where part of the col_name is NULL, where the col_name is a column declared not NULL, MySQL finds a match Stop after one line of the join condition (for a specific keyword combination) to search for additional rows.

The execution of the right join is similar to a left join, but the role of the table is reversed.

Joins the optimizer in the order in which the tables should be joined. Left JOIN and Straight_join forced table read Order can help the Join optimizer work faster because fewer table exchanges are checked. Note that this means that if you perform the following type of query, MySQL performs a full scan of B because the 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 fix is in the reverse order of a, 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 for the resulting null row, the Where condition is always false, and the left join becomes a normal join.

For example, in the following query, if T2.COLUMN1 is the Null,where clause, it will be 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 can be faster because MySQL can use table t2 before table T1 If you can make the query better. To enforce the use of 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.