1

I Have an order table in which i insert all the items that my customer placed in his order in single row.like

Table_ORDER ( Od_id is primary key auto incrementd)

Od_Id    Cust_Name  Quantity of 101(int)    Quantity of 102       Quantity of 103
-----     -------   --------------------       ---------------    --------------
1          John          5                          4                  7
2           Kim           4                          3                  2

Another Table of Price is like

Table_ Price 

Prod_ID      Price (money)
-------      ------
101           5.2
102           2.5
103           3.5

Now I want to get the total amount of specific order placed by customer. Problem is that if i use differnt rows for different item that Order id will be changed and if i use single row then How I calculate the total price as i can put jst single Prod_ID colum.

Kindly Guide me and send some solutions

Regards

4

2 回答 2

1

我确实看到表设计违反了大多数设计值,表之间没有外键。

但是您的问题的最坏情况解决方案在这里:

select ( q101*price101.price+q102*price102.price) as 'Total Price' from
(select p.id, q101, price from `order`, price p where p.id=101) as price101,
(select p.id, q102, price from `order`, price p where p.id=102) as price102,
(select p.id, q103, price from `order`, price p where p.id=103) as price103

我只是想建立表来连接你的两个表,然后基于它进行查询。

但随着产品数量的增加,它变得乏味。我真的建议考虑一个设计替代方案。

注意:我选择了这样的列名: 101 的数量 = q101

于 2013-04-20T08:07:34.363 回答
0

“问题是,如果我对不同的项目使用不同的行,则订单 ID 将被更改”。如果您通过将订购的产品和数量移动到通过外键与主订单表相关的单独表中来更改数据库的设计,这很容易解决。

这是一个非常简单的例子:

三个表,定义如下:

表顺序
------------
OrderID(身份列)
顾客姓名

表订单详情
------------------
OrderID(这是 Order 表中的外键)
ProductID(这是 Products 表中的外键)
数量

餐桌产品
--------------
产品编号
价格

现在,您可以通过执行如下查询来获取给定订单的总数:

SELECT SUM(ISNULL(od.Quantity, 0) * p.Price)
FROM   Orders o
JOIN   OrderDetail od
       ON o.OrderID = od.OrderID
JOIN   Products p
       ON od.ProductID = p.ProductID
WHERE  OrderID = 1

对于客户 1 (John),结果为 60.50。对于客户 2 (Kim),结果为 35.30(基于您问题中的数据)。

这种设计的好处是允许您将产品添加到 Products 表中,而无需更改 Orders 表的架构(列)。

同样,这是一个非常简单的示例,只是为了说明这个概念。

于 2013-04-20T19:15:12.817 回答