MySQL JOIN Types
SELECT from two tables
SELECT * FROM Table1;
SELECT * FROM Table2;
INNER JOIN
SELECT *
 FROM Table1 t1
INNER JOIN Table2 t2
   ON t1.fk = t2.id;
LEFT OUTER JOIN
SELECT *
 FROM Table1 t1
LEFT OUTER JOIN Table2 t2
 ON t1.fk = t2.id;
RIGHT OUTER JOIN
SELECT *
 FROM Table1 t1
RIGHT OUTER JOIN Table2 t2
 ON t1.fk = t2.id;
SEMI JOIN – Similar to INNER JOIN, with less duplication.
SELECT *
FROM Table1 t1
WHERE EXISTS (SELECT 1
               FROM Table2 t2
               WHERE t1.fk = t2.id
            );
ANTI SEMI JOIN
SELECT *
FROM Table1 t1
WHERE NOT EXISTS (SELECT 1  
                   FROM Table2 t2
                   WHERE t1.fk = t2.id
                );
LEFT OUTER JOIN with exclusion
SELECT *
 FROM Table1 t1
LEFT OUTER JOIN Table2 t2
  ON t1.fk = t2.id
WHERE t2.id is null;
RIGHT OUTER JOIN with exclusion
SELECT *
 FROM Table1 t1
RIGHT OUTER JOIN Table2 t2
  ON t1.fk = t2.id
WHERE t1.fk is null;
FULL OUTER JOIN
SELECT * FROM Table1 t1
 LEFT OUTER JOIN Table2 t2
  ON t1.fk = t2.id
UNION
SELECT * FROM Table1 t1
 RIGHT OUTER JOIN Table2 t2
  ON t1.fk = t2.id;
FULL OUTER JOIN with exclusion
SELECT * FROM Table1 t1
 LEFT OUTER JOIN Table2 t2
  ON t1.fk = t2.id
 WHERE t2.id IS NOT NULL
UNION
SELECT * FROM Table1 t1
 RIGHT OUTER JOIN Table2 t2
  ON t1.fk = t2.id
 WHERE t1.ID IS NOT NULL;
Two INNER JOINs
SELECT *
 FROM Table1 t1
INNER JOIN Table2 t2
  ON t1.fk = t2.id
INNER JOIN Table3 t3
  ON t1.fk_table3 = t3.id;
Two LEFT OUTER JOINS
SELECT *
 FROM Table1 t1
LEFT OUTER JOIN Table2 t2
  ON t1.fk = t2.id
LEFT OUTER JOIN Table3 t3
  ON t1.fk_table3 = t3.id;
INNER JOIN and a LEFT OUTER JOIN
SELECT *
 FROM Table1 t1
INNER JOIN Table2 t2
  ON t1.fk = t2.id
LEFT OUTER JOIN Table3 t3
  ON t1.fk_table3 = t3.id;
by გიორგი ბაკაშვილი
4 years ago
MySQL
JOIN
2
Pro tip: use ```triple backticks around text``` to write in code fences