DATEDIFF未在触发器内相乘

时间:2019-04-07 12:40:18

标签: mysql

嘿,每个人都有一个触发器,可以为每个客户计算发票。因此,我想查看应付金额取决于他们租车多少天!

DELIMITER //
CREATE TRIGGER update_booking_price_day 
BEFORE update ON bookings
FOR EACH ROW BEGIN 
SET NEW.TheDuration  = DATEDIFF(NEW.end_date, NEW.start_date);
SET NEW.AMOUNT_DUE  = DATEDIFF(NEW.end_date, NEW.start_date);  * SELECT rate_per_day FROM vehicles WHERE vehicle_id=NEW.vehicle_id; 
END;
//
DELIMITER ; 

表结构

   CREATE TABLE  bookings  (
   booking_id  int(50)  NOT NULL AUTO_INCREMENT,
   booking_date  date NOT NULL,
   start_date  date NOT NULL,
   end_date  date NOT NULL,
   invoice_no int(10)  NOT NULL ,
   chauffeur_id int(10) NULL,
   vehicle_id int(10)  NOT NULL ,
   customer_id int(50) NOT NULL ,
   chauffeur_req ENUM('Yes','No') NOT NULL,
   special_instructions varchar(255) NOT NULL,
   PRIMARY KEY (booking_id),
   KEY invoice_nofk2 (invoice_no),
   KEY chauffeur_idfk1 (chauffeur_id),
   KEY customer_idfk2 (customer_id),
   KEY vehicle_idfk2 (vehicle_id),
   CONSTRAINT invoice_nofk1 FOREIGN KEY (invoice_no) REFERENCES invoice (invoice_no),
   CONSTRAINT chauffeur_idfk2 FOREIGN KEY (chauffeur_id) REFERENCES chauffeurs (chauffeur_id),
   CONSTRAINT customer_idfk3 FOREIGN KEY (customer_id) REFERENCES customers (customer_id), 
   CONSTRAINT vehicle_idfk3 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE bookings
ADD COLUMN TheDuration varchar(10) NOT NULL;

ALTER TABLE bookings
ADD COLUMN AMOUNT_DUE varchar(16) NOT NULL; 

CREATE TABLE  vehicles (
   vehicle_id  int(10)  NOT NULL AUTO_INCREMENT,
   category ENUM('Sedan','Hatchback','SUV', 'Coupe', 'Crossover') NOT NULL,
   no_of_seats  int(11) NOT NULL,
   brand  varchar(20) NOT NULL,
   model  varchar(20) NOT NULL,
   product_year  int(5) NOT NULL,
   rate_per_day  int(11) NOT NULL,
   PRIMARY KEY (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我说一个错误...

1064-您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获取正确的语法,以在'* SELECT rate_per_day FROM vehicle WHERE vehicle_id = NEW.vehicle_id;

附近使用

END',位于第5行

1 个答案:

答案 0 :(得分:0)

您必须删除;之后的DATEDIFF(NEW.end_date, NEW.start_date),并将select语句括在括号内:

SET NEW.AMOUNT_DUE  = 
  DATEDIFF(NEW.end_date, NEW.start_date) * 
  (SELECT rate_per_day FROM vehicles WHERE vehicle_id=NEW.vehicle_id);

如果select语句仅返回1行,这将起作用。