Self-join pairs (and mutual pairs)
The half-open comparison is what turns a cross product into clean pairs.
The task
You want every pair of customers in the same region, each pair listed once, to introduce them to each other.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT a.name AS customer_a, b.name AS customer_b, a.region
FROM customers a
JOIN customers b
ON a.region = b.region
AND a.id < b.id
ORDER BY a.region, a.name;
它的運作方式
The self-join matches every customer row to every other row with the same region. The extra condition a.id < b.id does two jobs: it removes the row joined to itself, and it keeps only one of the (A, B) and (B, A) orderings, so each pair appears exactly once. For a mutual-pairs list where both directions matter, relax the condition to a.id <> b.id.
Variations
Mutual pairs: both directions
SELECT a.name AS customer_a, b.name AS customer_b, a.region
FROM customers a
JOIN customers b
ON a.region = b.region
AND a.id <> b.id
ORDER BY a.region, a.name;
Questions that come up
Why a.id < b.id and not just DISTINCT?
DISTINCT cannot remove (B, A) because the column values are swapped, so the rows differ. The inequality picks a canonical direction once, which is cheaper and clearer than deduplicating after the fact.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.