Для MySql 8.0+ вы можете использовать CTE:
with cte as (
select id, sum(t2.col) as cola, sum(t3.col) as colb, sum(t4.col) as colc
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
group by t1.id
)
select c.*, null as total
from cte as c
union all
select null, null, null, null, sum(cola + colb + colc)
from cte
Для более ранних версий:
select id, sum(t2.col) as cola, sum(t3.col) as colb, sum(t4.col) as colc, null as total
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
group by t1.id
union all
select null, null, null, null, sum(t2.col + t2.col + t2.col)
from t1
left join t2 on t2.id = t1.t2fk
left join t3 on t3.id = t1.t3fk
left join t4 on t4.id = t1.t4fk
В случае, если в столбцах null
s t2.col
, t3.col
и t4.col
вместо
sum(t2.col + t2.col + t2.col)
используйте:
sum(t2.col) + sum(t2.col) + sum(t2.col)