create table orders
(
customerid int NOT NULL,
orderid int NOT NULL
);
create table discounts
(
id int NOT NULL,
value int NOT NULL
);
create table customers
(
id int not null,
name varchar(20) not null,
phone varchar(20) not null
);
create table orderitems
(
orderid int NOT NULL,
productid int NOT NULL,
discount_code int NULL
);
create table products
(
productid int not null,
name varchar(20) not null,
productprice int not null
);
insert into customers
values
(1, "TEST NAME", "TEST PHONE");
insert into orders
values
(1, 1),
(2, 1);
insert into discounts
values
(1, 3),
(2, 3);
insert into orderitems
values
(1, 1, 2),
(1, 1, null);
insert into products
values
(1, "Product Name", 39);
SELECT sum(if(orderitems.discount_code is not null, products.productprice - discounts.value, products.productprice)), customers.name, customers.phone
FROM `customers`
inner join orders on customers.id = orders.customerid
inner join orderitems on orders.orderid = orderitems.orderid
left join discounts on discounts.id = orderitems.discount_code
inner join products on orderitems.productid = products.productid WHERE customers.id = "1";