I'm not pretty good in SQL but there is something that I suspect can be improved in the following query and I can't find a proper way to do it. The main problem is that the full query (I'm showing just a part of the query) is a bit slow and probably this is a point to improve the performance. So I have this simplified query:
SELECT
tableAa.name as Aa_Name,
tableAu.name as Au_Name,
tableA.code as A_Code,
(select qla.value
from tableQ as q
left join tableQL as ql on ql.q_id = q.id
left join tableQLA as qla on qla.ql_id = ql.id
left join tableQa as qa on qla.qa_id = qa.id
where ql.enabled is TRUE and ql.archived is FALSE and q.name = 'Some name for tableS'
and qa.id = tableS.qa_id
) as "Some alias for tableS",
(select qla.value
from tableQ as q
left join tableQL as ql on ql.q_id = q.id
left join tableQLA as qla on qla.ql_id = ql.id
left join tableQa as qa on qla.qa_id = qa.id
where ql.enabled is TRUE and ql.archived is FALSE and q.name = 'Other name for tableS'
and qa.id = tableS.qa_id
) as "Other alias for tableS",
-- more subqueries with exactly the same conditions, except the q.name and alias
(select qla.value
from tableQ as q
left join tableQL as ql on ql.q_id = q.id
left join tableQLA as qla on qla.ql_id = ql.id
left join tableQa as qa on qla.qa_id = qa.id
where ql.enabled is TRUE and ql.archived is FALSE and q.name = 'Some name for tableA'
and qa.id = tableA.qa_id
) as "Some alias for tableA",
(select qla.value
from tableQ as q
left join tableQL as ql on ql.q_id = q.id
left join tableQLA as qla on qla.ql_id = ql.id
left join tableQa as qa on qla.qa_id = qa.id
where ql.enabled is TRUE and ql.archived is FALSE and q.name = 'Other Value for tableA'
and qa.id = tableA.qa_id
) as "Other alias for tableA",
-- more subqueries with exactly the same conditions, except the q.name and alias
FROM tableS
LEFT JOIN tableA on tableS.a_id = tableA.id
LEFT JOIN tableAa on tableA.aa_id = tableAa.id
LEFT JOIN tableAu on tableA.au_id = tableAu.id
LEFT JOIN tableQa on tableA.qa_id = tableQa.id
WHERE
--Conditions
ORDER BY --Conditions
As you can notice, basically all subqueries are the same except for the where condition (q.name and tableS vs tableA) and for the alias (as 'Different values for each subquery')
Since I see a pattern here, I'm suspecting that it can be improved 'easily', but every single try just ended up in a not good result (surely due to my lack of knowledge). Can anyone help, please?
Thanks in advance!