返回在触发器中使用的值的函数

时间:2019-04-28 17:28:41

标签: mysql function triggers mariadb

我需要创建一个函数,以使驱动程序返回的交付次数最少。我有一个orders表,在该表中将驱动程序插入到适当的列中(值可以为NULL),以及分配了驱动程序的表餐厅。表驱动程序和表顺序的结构如下。

我试图做:

SELECT driver, restaurant, count(driver)
FROM orders 
GROUP BY restaurant, driver AS t;

现在,我应该从条件为driver.driver= t.driver and driver.restaurant=t.restaurant的表驱动程序中选择驱动程序,以及如何选择count(driver)最小的驱动程序。

CREATE TABLE IF NOT EXISTS `driver` (
  `Car_Number` varchar(10) NOT NULL,
  `Driver_Name` varchar(50) NOT NULL,
  `Model` varchar(50) NOT NULL,
  `Restaurant_Name` varchar(50) NOT NULL,
  PRIMARY KEY (`Car_Number`),
  KEY `FK_driver_car` (`Model`),
  KEY `FK_driver_restaurant` (`Restaurant_Name`),
  CONSTRAINT `FK_driver_car` FOREIGN KEY (`Model`) REFERENCES `car` (`Model`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `FK_driver_restaurant` FOREIGN KEY (`Restaurant_Name`) REFERENCES `restaurant` (`Restaurant_Name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `orders` (
  `Order_ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `Customer_Name` varchar(50) NOT NULL,
  `Restaurant_Name` varchar(50) NOT NULL,
  `Is_Delivery` varchar(3) NOT NULL,
  `Car_Number` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`Order_ID`),
  KEY `FK_order_customer` (`Customer_Name`),
  KEY `FK_order_restaurant` (`Restaurant_Name`),
  KEY `FK_order_driver` (`Car_Number`),
  CONSTRAINT `FK_order_customer` FOREIGN KEY (`Customer_Name`) REFERENCES `customer` (`Customer_Name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `FK_order_driver` FOREIGN KEY (`Car_Number`) REFERENCES `driver` (`Car_Number`) ON DELETE SET NULL ON UPDATE SET NULL,
  CONSTRAINT `FK_order_restaurant` FOREIGN KEY (`Restaurant_Name`) REFERENCES `restaurant` (`Restaurant_Name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1;

如果我的订单中有一位司机说2次送货,而一位司机说4次送货(对于同一家餐厅),我希望函数返回car_number(driver id)到拥有2位司机的驾驶员。

CREATE  DEFINER=root@localhost TRIGGER select_driver
      AFTER  INSERT   ON orders
    FOR EACH ROW BEGIN
        set @orderid = ( SELECT  max(order_id) from  orders );
        SET @restauranatname= ( SELECT  Restaurant_Name from  orders
                                           WHERE  order_id=@orderid );
        set @drivername = ( SELECT  find_lazy_driver('@restauranatname') );
        SET @car_number = ( SELECT  car_number FROM  driver
                                           WHERE  driver_name=@drivername );
        update  orders SET car_number= @car_number
            WHERE  Order_ID = @orderid;
        END

0 个答案:

没有答案