1

三表如下

mysql> select * from food;
+--------+------+-------+
| foodid | name | price |
+--------+------+-------+
|      1 | 雞   |   100 |
|      2 | 鴨   |   200 |
|      3 | 魚   |   300 |
|      4 | 肉   |   400 |
+--------+------+-------+
4 rows in set

mysql> select * from drink;
+---------+------+-------+
| drinkid | name | price |
+---------+------+-------+
|       1 | 紅茶 |    50 |
|       2 | 綠茶 |   100 |
|       3 | 奶茶 |   150 |
+---------+------+-------+
3 rows in set

mysql> select * from order_table;
+----+-----------+--------+---------+------------+-------------+-------------+
| id | user_name | foodid | drinkid | food_count | drink_count | total_price |
+----+-----------+--------+---------+------------+-------------+-------------+
|  2 | 小明      |      3 |       2 |          2 |           2 |           0 |
|  3 | 小華      |      1 |       1 |          1 |           8 |           0 |
|  4 | 小英      |      1 |       3 |          3 |           3 |           0 |
|  6 | 小a       |      2 |       1 |          4 |           6 |           0 |
|  7 | 小b       |      2 |       2 |          5 |           4 |           0 |
|  8 | 小c       |      2 |       3 |          6 |          10 |           0 |
|  9 | 大A       |      3 |       1 |          9 |           8 |           0 |
| 10 | 大B       |      3 |       2 |          5 |           4 |           0 |
| 11 | 大C       |      3 |       3 |         10 |           3 |           0 |
+----+-----------+--------+---------+------------+-------------+-------------+

order_table 中的 foodid 是指向食物表
中的 foodid 的链接,order_table 中的 drinkid 是指向饮料表中的 drinkid 的链接,

现在,我想计算总价,

Total_price = 
    order_table.foodid(food.price in food table) * order_table.food_count +
    order_table.drinkid(drink.price in drink table) * order_table.drink_count;

所以,让我知道更新总价的命令

多谢。

4

2 回答 2

2

我在以下查询中使用的原因LEFT JOIN是因为我假设某些订单可能只包含drinksor foods

UPDATE  order_table a
        LEFT JOIN food b
            ON a.foodid = b.foodID
        LEFT JOIN drink c
            ON a.drinkID = c.drinkID
SET     a.total_price = (a.food_count * COALESCE(b.price, 0) +
                        a.drink_count * COALESCE(c.price, 0))

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-03-04T03:02:44.433 回答
0

这样的事情应该很接近:

SELECT COALESCE(F.Price,0)*OT.Food_Count+COALESCE(D.Price,0)*OT.Drink_Count Total_price 
FROM Order_Table OT
    LEFT JOIN Food F ON OT.FoodId = F.FoodId
    LEFT JOIN Drink D ON OT.DrinkId = D.DrinkId

并实际更新该列:

UPDATE Order_Table OT
    LEFT JOIN Food F ON OT.FoodId = F.FoodId
    LEFT JOIN Drink D ON OT.DrinkId = D.DrinkId
SET OT.Total_Price =  COALESCE(F.Price,0)*OT.Food_Count+COALESCE(D.Price,0)*OT.Drink_Count
于 2013-03-04T03:01:15.047 回答