MySQL DAY8 multi-table query

multi-table query

One: Cartesian product

1. Suppose there are two sets X and Y, then the Cartesian product of X and Y is all possible combinations of X and Y.

2. If the multi-table query lacks the multi-table connection condition, the returned result may have a Cartesian product error.

例:SELECT employee_id,job_id

FROM employees,departments // From employees CROSS JOIN departments;

#The above statement will cause all employee_id and job_id in the two tables to be cross-connected, resulting in a Cartesian product error

3. Possible reasons for Cartesian product error:

a. Omit the join conditions of multiple tables;

b. The connection condition is invalid;

c. All rows in all tables are joined to each other.

Two: Multi-table query

1. Add valid connection conditions after WHERE:

SELECT table1.colum,table2.colum

FROM table1,table2

WHERE table1.colum1 = table2.colum2; #Connection conditions

2. If a field that exists in multiple tables appears in the query statement, the table of the field must be specified.

For example, job_id exists in both table1 and table2, and the query needs to FROM table1 and table2; it should SELECT table1.job_id or table2.job_id.

3. From the perspective of SQL optimization, it is recommended that when querying multiple tables, add the table it is in before each field.

4. You can alias the table, use the alias of the table in SELECT and WHERE to make the code more concise: FROM original table name table alias;

***Once an alias is given to the table, when the table name is used in SELECT and WHERE, only the alias of the table can be used, and the original name of the table cannot be used.

***This is different from the alias of the column. After the alias is listed, the original name can still be used

Example: Query employee's employee_id, last_name, department_name, city

SELECT e.employee_id,e.last_name,d.department_name,l.city

FROM employees e,departments d,locations l

WHERE e.department_id = d.department_id #Join condition of table e and table d

AND d.location_id = l.location_id; #Join condition of table d and table l

#If there are n tables that require multi-table query, at least n-1 connection conditions are required. If there are less than n-1, a Cartesian product error will occur.

おすすめ

転載: blog.csdn.net/m0_73249076/article/details/129393824