TExcelTAD
Home › MySQL › MySQL CROSS JOIN and Self Join

MySQL CROSS JOIN and Self Join

Two more join patterns complete the picture: the cross join, which pairs every row with every row, and the self join, where a table is joined to itself.

CROSS JOIN

A CROSS JOIN B returns every combination of a row from A with a row from B, the Cartesian product. There is no ON clause. With 3 and 4 rows you get 3 × 4 = 12 rows:

mysql · try it yourself
CREATE TABLE sizes  (size VARCHAR(5));
CREATE TABLE colors (color VARCHAR(6));
INSERT INTO sizes  VALUES ('S'), ('M'), ('L');
INSERT INTO colors VALUES ('red'), ('green'), ('blue'), ('black');

SELECT size, color
FROM sizes CROSS JOIN colors
ORDER BY FIELD(size, 'S', 'M', 'L'), color;
+------+-------+
| size | color |
+------+-------+
| S    | black |
| S    | blue  |
| S    | green |
| S    | red   |
| M    | black |
| M    | blue  |
| M    | green |
| M    | red   |
| L    | black |
| L    | blue  |
| L    | green |
| L    | red   |
+------+-------+

That is exactly what you need to generate all variants of a T-shirt. (FIELD(x, 'S', 'M', 'L') returns the position of x in the list, a handy way to sort by a custom order.)

Cross joins are also useful for comparing every row against a single summary row:

mysql · try it yourself
SELECT p.name, p.unit_price, ROUND(p.unit_price / s.avg_price * 100) AS pct_of_avg
FROM products AS p
CROSS JOIN (SELECT AVG(unit_price) AS avg_price FROM products) AS s
WHERE p.category_id = 1;
+----------------------+------------+------------+
| name                 | unit_price | pct_of_avg |
+----------------------+------------+------------+
| Espresso Beans 1kg   |      24.50 |        429 |
| Earl Grey Tea        |       6.75 |        118 |
| Orange Juice 1L      |       3.20 |         56 |
| Sparkling Water 6x1L |       4.99 |         87 |
+----------------------+------------+------------+

Warning: An accidental cross join, from a forgotten ON or a comma join without a WHERE, multiplies the row counts of the tables. Two tables of 10,000 rows give 100 million rows. If a query suddenly returns far too many rows, look for a missing join condition.

Self join

A self join joins a table to itself. You need it when rows of a table refer to other rows of the same table. In employees, manager_id holds the employee_id of the person's manager. To show each employee next to their manager's name, we use the table twice, under two aliases:

mysql · try it yourself
SELECT e.first_name AS employee, e.title, m.first_name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;
+----------+-------------------+---------+
| employee | title             | manager |
+----------+-------------------+---------+
| Grace    | CEO               | NULL    |
| Alan     | Sales Manager     | Grace   |
| Ada      | Warehouse Manager | Grace   |
| Linus    | Sales Rep         | Alan    |
| Maya     | Sales Rep         | Alan    |
| Omar     | Sales Rep         | Alan    |
| Tom      | Packer            | Ada     |
| Sara     | Packer            | Ada     |
+----------+-------------------+---------+

Think of e and m as two copies of the table. We used a LEFT JOIN so that Grace, who has no manager, is kept.

Comparing rows of the same table

Self joins also find pairs of related rows. "Which customers live in the same city?":

mysql · try it yourself
SELECT a.first_name AS customer1, b.first_name AS customer2, a.city
FROM customers AS a
JOIN customers AS b
  ON a.city = b.city AND a.customer_id < b.customer_id;
+-----------+-----------+--------+
| customer1 | customer2 | city   |
+-----------+-----------+--------+
| Ben       | George    | London |
+-----------+-----------+--------+

The condition a.customer_id < b.customer_id matters: without it, every customer would be paired with themselves, and each real pair would appear twice (Ben–George and George–Ben).

Counting through a self join works too, for example the number of direct reports of each manager:

mysql · try it yourself
SELECT m.first_name AS manager, COUNT(*) AS direct_reports
FROM employees AS m
JOIN employees AS e ON e.manager_id = m.employee_id
GROUP BY m.employee_id, m.first_name
ORDER BY direct_reports DESC, manager;
+---------+----------------+
| manager | direct_reports |
+---------+----------------+
| Alan    |              3 |
| Ada     |              2 |
| Grace   |              2 |
+---------+----------------+

Test yourself

Table A has 5 rows and table B has 4. How many rows does A CROSS JOIN B return?

  1. 9
  2. 5
  3. 20
  4. 4

What is required to join a table to itself?

  1. A special SELF JOIN keyword
  2. Two different aliases for the table
  3. A view
  4. A foreign key to another table

Why add a.customer_id < b.customer_id when pairing customers of the same city?

  1. To sort the result
  2. To avoid pairing a row with itself and listing each pair twice
  3. It's required syntax
  4. To speed up the query only