title: 03-Join
date: 2023-11-17
status: DONE
tags:
- MySQL
- NOTE
- Lec3
author:
- AllenYGY
created: 2023-11-17T18:18
updated: 2024-03-21T21:45
publish: True
Join
SELECT *
FROM table1
NATURAL JOIN table2;
默认JOIN所有共同的attribute
SELECT *
FROM table1
JOIN table2 ON table1.column_name = table2.column_name
JOIN table3 ON table2.column_name = table3.column_name;
SELECT *
FROM table1
JOIN table2 USING (column_name)
JOIN table3 USING (column_name);
SELECT *
FROM left_table
LEFT JOIN right_table ON left_table.column_name = right_table.column_name;
SELECT *
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
SELECT *
FROM table1
FULL JOIN table2 ON table1.column_name = table2.column_name;
The NATURAL JOIN operator associates two tables by the common attributes.
After NATURAL JOIN, the duplicated attributes are omitted.
SELECT * FROM city NATURAL JOIN country
is implemented as
SELECT city.country_id, city.last_update, city_id, city, country
FROM city, country
WHERE city.country_id = country.country_id AND
city.last_update = country.last_update
For example, these queries are equivalent.
SELECT first_name, last_name, address, district, postal_code
FROM customer NATURAL JOIN address
SELECT first_name, last_name, address, district, postal_code
FROM customer JOIN address ON customer.address_id = address.address_id AND customer.last_update = address.last_update
SELECT first_name, last_name, address, district, postal_code
FROM customer JOIN address USING (address_id, last_update)
SELECT * FROM city NATURAL JOIN country
is equivalent to
SELECT city.country_id, city.last_update, city_id, city,country
FROM city, country
WHERE city.country_id = country.country_id AND
city.last_update = country.last_update
SELECT *FROM table1 NATURAL JOIN table2 NATURAL JOIN table3
The query is understood as
SELECT* FROM (table1 NATURAL JOIN table2) NATURAL JOIN table3
只保留相同的部分
Notes:
当需要无法匹配的部分时
OUTER JOIN can handle it.
table1 NATURAL LEFT OUTER JOIN table2
All tuples in table1 are in the result. For the unmatched tuples, the values of the attributes from table2 are NULL, meaning “unknown”. (NULL values will be introduced in following labs.)
table1 NATURAL RIGHT OUTER JOIN table2
The unmatched tuples from table2 are kept.
table1 NATURAL FULL OUTER JOIN table2
All tuples (from both table1 and table2) are kept.
NATURAL is the join condition.
On the opposite of OUTER, INNER JOIN does not keep the unmatched tuples.
Same as JOIN. “INNER” is usually omitted.
Suppose we try to join this 2 tables
SELECT * FROM person NATURAL LEFT OUTER JOIN address
SELECT * FROM person NATURAL RIGHT OUTER JOIN address
SELECT * FROM person NATURAL FULL OUTER JOIN address