WITH CanonicalLayouts AS (
  SELECT regionId, MIN(layoutId) AS layoutId
  FROM MapLayouts
  GROUP BY regionId
),
RegionLayouts AS (
  SELECT
    re.regionId,
    re.regionName,
    cl.layoutId
  FROM Regions re
  JOIN CanonicalLayouts cl ON re.regionId = cl.regionId
),
SystemConnections AS (
  SELECT
    ss_from.solarSystemId AS fromSystemId,
    ss_to.solarSystemName AS toSystemName
  FROM StarGates sg
  JOIN SolarSystems ss_from ON sg.fromSystemId = ss_from.solarSystemId
  JOIN SolarSystems ss_to ON sg.toSystemId = ss_to.solarSystemId
),
ConnectedSystems AS (
  SELECT
    fromSystemId,
    GROUP_CONCAT(DISTINCT toSystemName) AS connectedSystems
  FROM SystemConnections
  GROUP BY fromSystemId
)
SELECT
  ss.solarSystemName AS solarSystemName,
  ml.x,
  ml.y,
  rl.regionName AS regionName,
  ss.security AS security,
  COALESCE(cs.connectedSystems, '') AS connectedSystems
FROM RegionLayouts rl
JOIN MapLayout ml ON ml.layoutId = rl.layoutId
JOIN SolarSystems ss ON ss.solarSystemId = ml.solarSystemId
LEFT JOIN ConnectedSystems cs ON ss.solarSystemId = cs.fromSystemId