这是我的数据库。FoodItems 只是普通表,但我想使用虚拟列来生成所有相关数据,例如 Servings.kcal 等于相关 (FieldItem.kcal*unit)/100(数据以每 100g/100ml 的千卡为单位指定):
CREATE TABLE IF NOT EXISTS `DietDB`.`Servings` (
`id` INT UNSIGNED NOT NULL,
`FoodItem_id` INT UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
`units` DOUBLE UNSIGNED NULL,
`kcal` INT GENERATED ALWAYS AS (SELECT (FoodItems.kcal*units)/100 FROM Servings JOIN FoodItems ON Servings.FoodItem_id = FoodItems.id) VIRTUAL,
`carbohydrate` DOUBLE UNSIGNED NULL,
`carbohydrate_sugar` DOUBLE UNSIGNED NULL,
`fat` DOUBLE UNSIGNED NULL,
`fat_saturated` DOUBLE UNSIGNED NULL,
`fat_trans` DOUBLE UNSIGNED NULL,
`protein` DOUBLE UNSIGNED NULL,
`fibre` DOUBLE UNSIGNED NULL,
PRIMARY KEY (`id`, `FoodItem_id`), …
Run Code Online (Sandbox Code Playgroud)