Jag var tvungen att ändra din utlösare eftersom den inte accepterade en sändning eller tredje rad
Som du kan se
Du kan komma åt alla nya är genom att använda NEW.product_id inget behov av ett urval alls
Nästa sak jag behövde ändra var att jag nu inte hade något id mer så jag använde NEW.product:id igen.
Schema (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");
Fråga #1
SELECT * FROM `range_and_prices`;
| id | ranges_from | ranges_to | prices |
| --- | ----------- | --------- | ------ |
| 1 | 1 | 20 | 10 |
| 2 | 21 | 40 | 20 |
| 3 | 41 | 60 | 40 |
Fråga #2
SELECT * FROM `product`;
| product_id | product | total_quantity |
| ---------- | ------- | -------------- |
| 1 | Coffee | 5 |
| 2 | sugar | 25 |
Fråga #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 |