WITH pairs AS (
	SELECT
		a.id AS id_a,
		b.id AS id_b
	FROM chara_data a
		JOIN chara_data b ON a.id < b.id
	-- Exclude characters who have no succession relations defined.
	WHERE a.id IN (SELECT chara_id FROM succession_relation_member)
		AND b.id IN (SELECT chara_id FROM succession_relation_member)
), trios AS (
	SELECT
		a.id AS id_a,
		b.id AS id_b,
		c.id AS id_c
	FROM chara_data a
		JOIN chara_data b ON a.id < b.id
		JOIN chara_data c ON a.id < c.id AND b.id < c.id
	-- Exclude characters who have no succession relations defined.
	WHERE a.id IN (SELECT chara_id FROM succession_relation_member)
		AND b.id IN (SELECT chara_id FROM succession_relation_member)
		AND c.id IN (SELECT chara_id FROM succession_relation_member)
), pair_relations AS (
	SELECT
		ra.relation_type,
		ra.chara_id AS id_a,
		rb.chara_id AS id_b
	FROM succession_relation_member ra
		JOIN succession_relation_member rb ON ra.relation_type = rb.relation_type
), trio_relations AS (
	SELECT
		ra.relation_type,
		ra.chara_id AS id_a,
		rb.chara_id AS id_b,
		rc.chara_id AS id_c
	FROM succession_relation_member ra
		JOIN succession_relation_member rb ON ra.relation_type = rb.relation_type
		JOIN succession_relation_member rc ON ra.relation_type = rc.relation_type
), affinity AS (
	SELECT
		pairs.*,
		0 AS id_c,
		SUM(IFNULL(relation_point, 0)) AS base_affinity
	FROM pairs
		LEFT JOIN pair_relations rp ON pairs.id_a = rp.id_a AND pairs.id_b = rp.id_b
		LEFT JOIN succession_relation sr ON rp.relation_type = sr.relation_type
	GROUP BY pairs.id_a, pairs.id_b

	UNION ALL

	SELECT
		trios.*,
		SUM(IFNULL(relation_point, 0)) AS base_affinity
	FROM trios
		LEFT JOIN trio_relations rt ON trios.id_a = rt.id_a AND trios.id_b = rt.id_b AND trios.id_c = rt.id_c
		LEFT JOIN succession_relation sr ON rt.relation_type = sr.relation_type
	GROUP BY trios.id_a, trios.id_b, trios.id_c
)
SELECT * FROM affinity
WHERE base_affinity != 0
ORDER BY id_a, id_b, id_c
