RIGHT, FULL, CROSS, self JOIN and week 4 review
You already master INNER and LEFT JOIN, which cover the vast majority of real cases. To complete the map you are missing three variants and one technique. RIGHT JOIN and FULL JOIN extend the idea of keeping rows without a match, CROSS JOIN generates all combinations and the self JOIN joins a table with itself. We will finish with a visual summary and a review of the week.
RIGHT JOIN and FULL JOIN
RIGHT JOIN is the mirror of LEFT JOIN: it keeps all rows of the right table. In practice almost nobody uses it, because it is enough to swap the order of the tables and use LEFT JOIN, which reads more naturally. FULL JOIN (FULL OUTER JOIN) keeps the unmatched rows of both sides: an unmatched left row comes out with NULL on the right and vice versa. It is useful to compare two lists and see what is missing from each. PostgreSQL supports it; MySQL has no FULL JOIN and it is simulated with a UNION of a LEFT and a RIGHT JOIN, while SQLite includes it since version 3.39.
-- RIGHT JOIN: every order, even if it had no customer row (here all have one)
SELECT o.order_id, c.name
FROM customers c
RIGHT JOIN orders o ON o.customer_id = c.customer_id;
-- FULL JOIN: customers and orders, keeping the unmatched on both sides
SELECT c.name, o.order_id
FROM customers c
FULL JOIN orders o ON o.customer_id = c.customer_id
ORDER BY c.name, o.order_id;In our shop the foreign key prevents orders without a customer, so the FULL JOIN only adds Felipe and Hugo with NULL in order_id. In real databases, where data from different systems is combined, FULL JOIN is a very useful auditing tool.
CROSS JOIN and self JOIN
CROSS JOIN pairs every row of one table with every row of the other, with no condition: 8 customers times 10 products give 80 combinations. It is rarely wanted, but you should recognize it because it appears by accident: if you forget the ON in a JOIN, or write FROM a, b without WHERE, you get a huge, slow Cartesian product. The self JOIN, on the other hand, is a legitimate technique: a table is joined with itself using two different aliases. It is the way to compare rows with each other, for example customers in the same city.
SELECT COUNT(*) AS combinations FROM customers CROSS JOIN products;
-- Pairs of customers who live in the same city (a.id < b.id avoids duplicates and self-pairs)
SELECT a.name AS customer_a, b.name AS customer_b, a.city
FROM customers a
JOIN customers b ON a.city = b.city AND a.customer_id < b.customer_id;
-- USING is a shortcut when both columns have the same name
SELECT o.order_id, c.name
FROM orders o JOIN customers c USING (customer_id);理解度チェック
問題 1 / 6What is a foreign key?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字