SQL query for records with at least one associated record

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.

Last Updated: 2022-12-01

How to get records A (say station_location) that have at least 1 of record B associated (say slots).

The trick is to use a subquery that references the parent query:

SELECT * FROM `station_locations` 
WHERE EXISTS (
  SELECT * 
  FROM `slots` 
  WHERE `station_locations`.`id` =
  `slots`.`station_location_id`
  )