create table Orders
(
id int NOT NULL,
price int NOT NULL,
discount_code int NULL
);
create table Discounts
(
id int not null,
value int not null
);
insert into Orders
values
(1, 10, null),
(2, 10, null),
(3, 5, 1),
(4, 25, 1);
insert into Discounts
values
(1, 3);
select sum(if(o.discount_code is not null, o.price - d.value, o.price))
from Orders as o
left join Discounts as d
on o.discount_code = d.id;
-- 10 + 10 + 2 + 22 = 44