0

I am programming a very simple payments web app which is my first attempt at programming anything. I've run into trouble with my database structure, with people saying it should be normalized.

At the moment I have the following structure.

Customers
---------
id, firstName, lastName, country

Items
---------
id, itemName, itemCost

Purchases
----------
customerID, dayCost, serviceCost, numItem1, numItem2, numItem3

Orders
----------
orderId, customerId, amountPaid, date

I need to be able to do a query where I can display the following:

  • Total : 140
  • Day Cost: 50
  • Service Cost: 70
  • Coronas Cost: 20 (4)
  • Item 2 Cost: 0
  • Item 3 Cost: 0
  • Total Owing: 100

My idea was to calculate, for example, ( purchases.numItem1 by item.itemName where id = 1 + purchases.dayCost + purchases.serviceCost ) - orders.amountPaid.

This isn't right and I'm not sure what it should be.

I need to be able to return in a query how much of each item the customer has ordered, the total cost for each item, and the total cost owing.

What is a better, normalized table structure to allow for this query?

I can't simply have an orders table with customer and item id and quantity and amount paid, because I have to work with a form on a webpage and that structure won't work.

4

1 回答 1

0

客户和项目可以在需要时扩展,但到目前为止还不错。

如果 daycost 和 servicecost 是每件商品,您可以将购买更改为

Purchases
----------
orderId, dayCost, serviceCost, itemid, itemsBought

现在您可以通过以下方式计算订单成本

select sum(p.itemsBought * i.itemcost + p.daycost + p.servicecost) as itemsCost
from purchases p
join items i on p.itemid = i.id
where p.orderid = 17

或客户欠款

select sum(p.itemsBought * i.itemcost + p.daycost + p.servicecost)
       - sum(o.amountPaid) as owing
from purchases p
join items i on p.itemid = i.id
join orders o on o.orderid = p.orderid
where o.customerid = 284
于 2012-12-05T07:02:32.853 回答