so I have a small problem whilst working with SQL and PHP. I have a sql db which has 4 tables namely, customers, requests, products and sellers. Now, each table contains self explanatory data. Such as customers tables lists the customers, ids, names, adresses, emails etc., products table has product id and the name, the requests table shows the request of products made by customers with the request id[pk], custID[fk from customer table], productid[fk in products table], quantites_requested, price_requested
. The sellers table contains data such as sellersid[pk], customerid[fk from customer table], productsid[fk in products table], quantites_advertised, price_advertised
Now what I wish to do, is say a customer has requested productid= 1(chocolate),customer id=1, 10kg has been requested for £10.00 So, this data is stored in the DB.
Now, there might be various sellers of chocolate and what I wish to do is fulfil the customers order i.e. 10kg of chocolates in the cheapest way possible. either by combining sellers or selecting one cheapest seller. So, for example, this is the sellers table. NOTE: the sellers table is structured by following: sellerid[pk],customerid[fk],productid[fk],quantity_advertised, price_advertised
. so here are some example sellers...
1,2,1,4.00,2.00 -- This means customer id 2 is selling chocolates, for 4KG's @£2.00
2,3,1,5.00,2.50
3,4,1,1.00,1.00
4,5,1,10.00,6.00
Now we have our requests that state
1,1,1,10.00,5.00 -- i.e. customer1, wants chocolates of 10kg for £5.00...
Now I wish to fulfil the customers 10kg order. So what I need to do is select the cheapest price for the customer. This could be done by selecting sellers 2,3 and 4 with the kg's of 5,4 and 1kg=10kg which would cost a total of £2.00+£2.50+£1.00=£5.50 cheaper then seller 5 which can supply 10KG for 6.00. I believe I would be able to do something like this using an SQL query where it first matches the customer requests product id to the sellers product id i.e. SELECT c.Name, p.Name, s.quantity,s.price WHERE c.id=s.customerid AND p.id=s.productid AND s.quantity WHERE r.productid=s.productid FROM requests r, sellers s
however, how would I be able to select the cheapest option supplier either combined or a single large supplier to take to be the most cost effective? I believe I would need to use the MIN somewhere in the query?
Can someone guide me on how to structure a query as stated. i.e. the full customer request needs to be met in the cheapest way possible.