SELECT
	x.id AS id,
	x.name AS name,
	(
		CASE
			WHEN MAX(y.level) IS NULL THEN x.access_level_default
			ELSE MAX(y.level)
		END
	) AS access_level
FROM
	calendars AS x
	LEFT OUTER JOIN calendar_access_attributed AS y ON ((x.id = y.calendar_id) AND (y.user_id = $user_id))
GROUP BY
	x.id
HAVING
	(access_level > 0)
ORDER BY
	access_level DESC,
	id
;
