更新多表中的数据

时间:2013-03-04 02:56:55

标签: mysql sql sql-update

以下三个表

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;

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

很多。

2 个答案:

答案 0 :(得分:2)

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

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))

要进一步了解联接,请访问以下链接:

答案 1 :(得分: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