SELECT
*
FROM data_entity a
LEFT JOIN list_dokumen b ON a.dokumen = b."id"
CASE WHEN b.pengirim_level == 1
THEN LEFT JOIN master_polda c ON c.id_polda = b.pengirim_level_id
WHEN b.pengirim_level == 2
THEN LEFT JOIN master_polres d ON d.id_polres = b.pengirim_level_id
WHEN b.pengirim_level == 3
THEN LEFT JOIN master_polsek e ON e.id_polsek = b.pengirim_level_id
WHEN b.pengirim_level == NULL
THEN NULL
END
答案 0 :(得分:3)
我认为您可以将查询重写为:
SELECT * FROM data_entity a
LEFT JOIN list_dokumen b ON a.dokumen = b."id"
LEFT JOIN master_polda c ON c.id_polda = b.pengirim_level_id and b.pengirim_level = 1
LEFT JOIN master_polres d ON d.id_polres = b.pengirim_level_id and b.pengirim_level == 2
LEFT JOIN master_polsek e ON e.id_polsek = b.pengirim_level_id and b.pengirim_level == 3
END
答案 1 :(得分:0)
您可以使用动态SQL根据PL / pgSQL函数内部的条件构造SQL。参见PL/pgSQL EXEC documentation
或者,您可以只连接所有三个表并使用coalesce
从其中一个表中获取必要的字段。
SELECT a.*, b.*, coalesce(c.FIELD, d.FIELD, e.FIELD)
FROM data_entity a
LEFT JOIN list_dokumen b ON a.dokumen = b."id"
LEFT JOIN master_polda c ON b.pengirim_level == 1 AND c.id_polda = b.pengirim_level_id
LEFT JOIN master_polres d ON b.pengirim_level == 2 AND d.id_polres = b.pengirim_level_id
LEFT JOIN master_polsek e ON b.pengirim_level == 3 AND e.id_polsek = b.pengirim_level_id