Jeg var nødt til at ændre din trigger, fordi den ikke accepterede en send eller tredje række
Som du kan se
Du kan få adgang til alt nyt ved at bruge NEW.product_id, slet ikke nødvendigt at vælge
Den næste ting, jeg skulle ændre, var, at jeg nu ikke havde noget id mere, så jeg brugte NEW.product:id igen.
Skema (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");
Forespørgsel #1
SELECT * FROM `range_and_prices`;
| id | ranges_from | ranges_to | prices |
| --- | ----------- | --------- | ------ |
| 1 | 1 | 20 | 10 |
| 2 | 21 | 40 | 20 |
| 3 | 41 | 60 | 40 |
Forespørgsel #2
SELECT * FROM `product`;
| product_id | product | total_quantity |
| ---------- | ------- | -------------- |
| 1 | Coffee | 5 |
| 2 | sugar | 25 |
Forespørgsel #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 |