This command joins two tables together but keeps all the rows from the left side and vice versa for the RIGHT JOIN.
\!h Simple example - left-joins newspaper and online using id
SELECT *
FROM newspaper
LEFT JOIN online
ON newspaper.id = online.id;
-- Outputs matching from the second table if it exists, and NULL if there's not matching data.
\!h List all tracks and show when each was played. *Include tracks that have never been played*
SELECT track_name, played FROM
track LEFT JOIN played USING (artist_id, album_id, track_id)
ORDER BY played DESC;
+----------------------------+---------------------+
| track_name | played |
+----------------------------+---------------------+
| Bizarre Love Triangle | 2006-08-14 10:54:02 |
| Crystal | 2006-08-14 10:47:21 |
| The Perfect Kiss | 2006-08-14 10:36:54 |
| True Faith | 2006-08-14 10:30:25 |
| Temptation | 2006-08-14 10:25:22 |
| Fine Time | 2006-08-14 10:21:03 |
| Elegia | NULL |
| Lonesome Tonight | NULL |
| Procession | NULL |
...
\!h RIGHT JOIN equivalent:
SELECT track_name, played FROM
played RIGHT JOIN track USING (artist_id, album_id, track_id)
ORDER BY played DESC;
\!h Above example more advanced:
SELECT artist_name, album_name, COUNT(played) FROM
artist INNER JOIN album USING (artist_id)
INNER JOIN track USING (artist_id, album_id)
LEFT JOIN played USING (artist_id, album_id, tar)