有dishes表(dno,dname,damount,dprice),有supply表(rno,dno,samount,sdate),有restaurants表(rno,rname,raddress,rphone),请设计一个统计表和触发器,并表明该触发器的作用
时间: 2024-01-22 16:18:27 浏览: 175
设计统计表如下:
```sql
CREATE TABLE statistics (
rname VARCHAR(50),
dname VARCHAR(50),
total_sales DECIMAL(10,2)
);
```
该表将记录每个餐厅的每道菜品的总销售额。
设计触发器如下:
```sql
CREATE TRIGGER update_statistics AFTER INSERT ON supply
FOR EACH ROW
BEGIN
DECLARE restaurant_name VARCHAR(50);
DECLARE dish_name VARCHAR(50);
DECLARE total_sales DECIMAL(10,2);
SELECT rname INTO restaurant_name FROM restaurants WHERE rno = NEW.rno;
SELECT dname INTO dish_name FROM dishes WHERE dno = NEW.dno;
SELECT SUM(damount * dprice) INTO total_sales FROM dishes WHERE dno = NEW.dno;
IF EXISTS(SELECT 1 FROM statistics WHERE rname = restaurant_name AND dname = dish_name) THEN
UPDATE statistics SET total_sales = total_sales + NEW.samount * dprice
WHERE rname = restaurant_name AND dname = dish_name;
ELSE
INSERT INTO statistics (rname, dname, total_sales) VALUES (restaurant_name, dish_name, NEW.samount * dprice);
END IF;
END;
```
该触发器的作用是在每次向供应表插入新记录时,更新统计表中对应餐厅和菜品的总销售额。具体实现方式是先查询该餐厅和菜品在统计表中是否已有记录,如果有则更新总销售额,否则插入新记录。其中用到了NEW关键字获取插入的新记录,以及IF EXISTS语句判断记录是否存在。
阅读全文