How to implement database multi-table connection query

Source: Internet
Author: User

The implementation of database multi-table connection query is the most important query in the relational database, mainly includingself-connect、Internal Connection、External ConnectionAndCross Connect。 You can implement multiple table queries by using the Join operator. Connection is the main feature of relational database model, and it is also a sign that distinguishes it from other types of database management system. In the relational database management system, the relationship between the data is not determined, and all the information of an entity is often stored in a single table. When retrieving data, the connection operation queries the information for different entities that reside in multiple tables. The connection operation gives the user a lot of flexibility and they can add new data types at any time. Create a new table for different entities, and then query through the connection.within the connection query result set contains only the rows that satisfy the condition, the internal connection is the SQL Server default connection method, can be shortened to join Innerjoin, according to the comparison method used, the internal connection is divided into equivalent connection, natural connection and unequal connection three kinds The cross-connected query result set contains a combination of all the rows in the two tables, and the outer join query result set contains both the rows that satisfy the criteria and all the rows of one of the tables, with 3 forms of outer joins: Left OUTER join, right outer join, and full outer join.  A cross-connected cross connection is a flute Descartes product, which refers to any combination of all tuples in two relationships.    In general, cross-query is of no practical significance. For example, if you want to get the product of the two relational patterns of the student table and the selected timetable, the query statement isSELECT * From Student table cross Join selection timetableTwo, inner connection is one of the most commonly used connection types. An inner join query is actually a query of any condition.    When using an inner join, if the related fields of two tables meet the join criteria, the data is extracted from both tables and the group synthesizes the new records, that is, in the inner join query, only tuples that meet the criteria can appear in the result relationship. For example, to query the situation of each student who has selected a class, the query statement isselect*From Student table inner JOIN select timetable on student table. Study Number = Choose a timetable. School NumberClassification: According to the comparison method is divided into:1) Equivalent connection: Use the equals sign (=) operator in the join condition to compare the column values of the concatenated columns, and the query results list all the columns in the joined table, including the repeating columns.2) Unequal connection: Use comparison operators other than the equals operator in the join condition to compare the column values of the connected columns. These operators include >, >=, <=, <,!>,!<, and <>.3) Natural Connection: Use the Equals (=) operator in the join condition to compare the column values of the connected column, but it uses the selection list to indicate which columns are included in the query result collection and to delete the duplicate columns in the Join table. Iii. Self-Connection if the two tables involved in a connection query are the same table, this query is called a self-join query. The same table appears multiple times in the FROM clause, in order to distinguish each occurrence of the table, you need to define an alias for the table.    A self-join is a special inner connection, which refers to a table that is connected to each other physically, but can be logically divided into two tables. For example: Ask to retrieve the information of the classmate of student number 20210, the query statement isSelect Student table. *From Student table join student table as Student Table 1ON Student table. class = Student Table 1. Classwhere student table 1. Study number = ' 20210 'The query results of the connections within the outer join are all tuples that satisfy the join condition. But sometimes we also want to output tuple information that does not meet the connection criteria. For example, we would like to know each student's choice of course, including the students who have already chosen the course (this part of the student's school number in the student table, also in the selection of curriculum, is to meet the connection conditions), but also includes the students who have no elective courses (this part of the student's school number in the student table, but in the Then you need to use an outer join. An outer join is one that restricts the data in one table to meet the join criteria, while the data in the other table does not meet the connection criteria. 3 Types of external connections:1) Left outer connection (Leftouter join)If in a connection query, all tuples in the table connecting the left side of the pipe are listed, and a matching tuple can be found in the table at the right end, the connection succeeds. If a matching tuple is not found in the right-hand table, then the corresponding tuple is null (NULL).    At this point, the query statement using the keyword left outerjoin, that is, the meaning of the outer join is to restrict the connection to the right side of the table data must meet the join conditions, and not the left side of the table data is satisfied with the join condition, both output the contents of the left side table. For example, to inquire about the course selection for all students, including those who have already chosen the course and those who have not yet selected the course, the query isSelect Student table. School number, name, class, course number, scoreFrom student table left OUTER join select schedule on student table. Study Number = Choose a timetable. School Numberinformation for all tuples in the left-hand table in the left OUTER join query is preserved. 2) Right outer connection (Rightouterjoin)The right outer join is similar to the left outer join, except that all tuples in the right-side table are listed, and the data that restricts the left-side table must satisfy the join condition, regardless of whether the data in the right-side table satisfies the join condition, and outputs the contents of the table. For example, in the above example, the query statement isSelect Student table. School number, name, class, course number, scoreFrom Student table Rightouterjoin Select the timetable on the student table. Study Number = Choose a timetable. School NumberThe information for all tuples in the right-side table in the right outer join query is preserved. 3) All-out connection (full OUTER join)The full outer join query is characterized by the output of tuples in both the left and right tables, using NULL instead if no matching tuples can be found. Example: With the LEFT OUTER join example, the query statement isSelect Student table. School number, name, class, course number, scoreFrom student table full OUTER join select Schedule on student table. Study Number = Choose a timetable. School NumberThe tuple information in all tables in the full outer join query is preserved.

V. Examples of applications
 2 take MySQL for example. Create two data tables in the MySQL database and insert some data separately. The 4 script is as follows: 5 drop table table1;  6 CREATE TABLE ' Andrew '. ' Table1 ' 7 (8 ' name ' varchar (+) not NULL, 9 ' city ' varchar (+) not NULL10) ENGINE = myisam;12 Insert into TABLE1 (name, city) VALUES (' Person A ', ' BJ ') and insert into TABLE1 (name, city) VALUES (' Person B ', ' BJ '); Nsert into TABLE1 (name, city) VALUES (' Person C ', ' SH '), and insert into TABLE1 (name, city) VALUES (' Person D ', ' SZ '); mit;17 drop table table2;18 CREATE table ' Andrew '. ' Table2 ' (the ' name ' varchar (+) not null,21 ' city ' varchar (+) not NUL L22) = myisam;24 insert into TABLE2 (name, city) VALUES (' Person W ', ' BJ '), insert into TABLE2 (name, city) Valu  ES (' Person X ', ' sh '), + INSERT into TABLE2 (name, city) VALUES (' Person Y ', ' sh '), and insert into TABLE2 (name, city) values (' Person Z ', ' NJ '); commit;29 1. External connection – Left connection results in Table1 left, so the left connection. In this case, all records in the Table1 are listed as table1. There are three cases: a. For each record in Table1, the city if it happens to be in table2, and there is just one, a new record is formed in the result returned by 32. As above person A and persOn B corresponds to the case. B. For each record in the Table1 the city if it happens to exist in Table2 and has n, it will form n new records in the returned results. such as the person C above corresponds to the case. C. For each record in table1 the city if it does not exist in the Table2, a 35 new record is formed in the returned result, and all null on the right side of the record. As in the case of person D above. 36 records that do not conform to the three rules above will not be listed. 37 2. External connection – Right connection result table2 right, so the right connection. In this case, all records in the table2 are listed as table2. There are three cases: a. For each of the records in table2 the city if it happens to be in Table1, and there is just one, a new record is formed in the result returned by 40. As in the case of person X and person y above. B. For each record in table2 the city if it happens to exist in Table1 and has n, then it will form N new records in the returned results. If the person W above corresponds to the case. C. For each record in table2 the city if it does not exist in the Table1, a 43 new record is formed in the returned result, and the left side of the record is all null. such as the person Z above corresponds to the case. 44 records that do not conform to the three rules above will not be listed. 45 3. In a data record that is connected within 46, there is no case of NULL in the field. It is easy to think that the result of the inner link is the result of rejecting the null record in the result of the left or right connection.
It is even possible to think that if only the data records of the two tables are left behind, such as only person A, person B, and person c,table2 in the Table1, only person W, person X, and person Y,
Then the result of the return of the left and right connections between the two tables is the same. 47 Note: SELECT * FROM table1 a inner joins table2 b on a.city = b.city and select * FROM table1 a joins table2 b on a.city = B.ci Ty's effect is the same,
That is, if the left side of the join does not have a keyword such as a inner, right or the other, the default is an inner join. Also, MySQL does not support full join.

How to implement database multi-table connection query

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.