Comparing a Table to Itself
Problem
You want to compare rows in a table to other rows in the same
table. For example, you want to find all paintings in your collection
by the artist who painted The Potato Eaters. Or
you want to know which states listed in the states table joined the Union in the same
year as New York. Or you want to know which states did not join the
Union in the same year as any other state.
Solution
Problems that require comparing a table to itself involve an operation known as a self-join. It’s performed much like other joins, except that you must always use table aliases so that you can refer to the same table different ways within the statement.
Discussion
A special case of joining one table to another occurs when both tables are the same. This is called a self-join. Although many people find the idea confusing or strange to think about at first, it’s perfectly legal. It’s likely that you’ll find yourself using self-joins quite often because they are so important.
A tip-off that you need a self-join is when you want to know which pairs of elements in a table satisfy some condition. For example, suppose that your favorite painting is The Potato Eaters, and you want to identify all the items in your collection that were done by the artist who painted it. Do so as follows:
Identify the row in the
paintingtable that contains the title The Potato Eaters, so that you can refer to itsa_idvalue.Use the
a_idvalue to match other rows in the table that have the samea_id ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access