Трябваше да променя тригера ви, защото не приемаше изпращане или трети ред
Както можете да видите
Можете да осъществите достъп до всичко ново, като използвате NEW.product_id, изобщо няма нужда от избор
Следващото нещо, което трябваше да променя, беше, че вече нямах идентификатор, така че отново използвах NEW.product:id.
Схема (MySQL v5.7)
CREATE TABLE `product` (
`product_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`product` varchar(100) NOT NULL,
`total_quantity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `range_and_prices` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`ranges_from` int(11) NOT NULL,
`ranges_to` int(11) NOT NULL,
`prices` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `range` (
`product_id` INT NOT NULL PRIMARY KEY,
`range_prices` int(11) NULL,
FOREIGN KEY (`product_id`) REFERENCES `product`(`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `range_and_prices` (`ranges_from`,`ranges_to`, `prices`) VALUES
('1','20', 10),
('21','40', 20),
('41','60', 40);
CREATE TRIGGER `range_on_product`
AFTER insert ON `product`
FOR EACH ROW
insert into `range`(`product_id`, `range_prices`) VALUES
(NEW.product_id , (SELECT DISTINCT prices FROM range_and_prices WHERE (SELECT total_quantity FROM product WHERE product_id=NEW.product_id) BETWEEN ranges_from AND ranges_to ORDER BY prices ASC
LIMIT 1 ) );
INSERT INTO `product` ( `product`, `total_quantity`) VALUES ("Coffee", "5"),("sugar", "25");
Заявка №1
SELECT * FROM `range_and_prices`;
| id | ranges_from | ranges_to | prices |
| --- | ----------- | --------- | ------ |
| 1 | 1 | 20 | 10 |
| 2 | 21 | 40 | 20 |
| 3 | 41 | 60 | 40 |
Заявка №2
SELECT * FROM `product`;
| product_id | product | total_quantity |
| ---------- | ------- | -------------- |
| 1 | Coffee | 5 |
| 2 | sugar | 25 |
Запитване #3
SELECT * FROM `product` INNER JOIN `range` ON product.product_id=range.product_id;
| product_id | product | total_quantity | product_id | range_prices |
| ---------- | ------- | -------------- | ---------- | ------------ |
| 1 | Coffee | 5 | 1 | 10 |
| 2 | sugar | 25 | 2 | 20 |