sql >> Base de Datos >  >> RDS >> Mysql

Selección de valores entre dos columnas en varias filas

Tuve que cambiar tu activador, porque no aceptaba un envío o una tercera fila

Como puedes ver

Puede acceder a todas las novedades usando NEW.product_id sin necesidad de seleccionar nada

Lo siguiente que necesitaba cambiar era que ya no tenía id, así que usé NEW.product:id nuevamente.

Esquema (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"); 

Consulta #1

SELECT * FROM `range_and_prices`;

| id  | ranges_from | ranges_to | prices |
| --- | ----------- | --------- | ------ |
| 1   | 1           | 20        | 10     |
| 2   | 21          | 40        | 20     |
| 3   | 41          | 60        | 40     |

Consulta #2

SELECT * FROM `product`;

| product_id | product | total_quantity |
| ---------- | ------- | -------------- |
| 1          | Coffee  | 5              |
| 2          | sugar   | 25             |

Consulta n.º 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           |

Ver en DB Fiddle