I have read numerous topics and articles and official MYSQL docs but nowhere I have find something that would help me understand how to solve this.
Even this SO topic failed to do what I need (in it, they didn't try to search value bigger then 2, you'll see why that is a problem).
For example I have ranges defined in range_and_prices table:
---
| id | ranges_from | ranges_to | prices |
| --- | ----------- | --------- | ------ |
| 1 | 1 | 20 | 10 |
| 2 | 21 | 40 | 20 |
| 3 | 41 | 60 | 40
When I try to insert product that have total_quantity 5;
| product_id | product | total_quantity |
| ---------- | ------- | -------------- |
| 1 | Coffee | 5 |
I get result of my quarry as It should be (as total_quantity is 5, it falls under range of 1-20 and range_prices for that is 10):
| product_id | product | total_quantity | product_id | range_prices |
| ---------- | ------- | -------------- | ---------- | ------------ |
| 1 | Coffee | 5 | 1 | 10 |
BUT as soon as I try to get into other ranges I get null for range_prices.
If in fiddle I chose 25 result should be:
| product_id | product | total_quantity | product_id | range_prices |
| ---------- | ------- | -------------- | ---------- | ------------ |
| 1 | Coffee | 25 | 1 | 20 |
But I am getting null, for anything that is above 20 total_quantity.
insert into `range`(`product_id`, `range_prices`) VALUES
((SELECT LAST_INSERT_ID() AS id FROM product ),
(SELECT prices FROM range_and_prices WHERE
(SELECT total_quantity FROM product WHERE product_id=id)
BETWEEN ranges_from AND ranges_to ORDER BY prices ASC
LIMIT 1 ) );
I believe I know why is that. If I chose for example 25, that number is in between 1 and 40, and result for that is two ranges and it gets confused. I tired all sort of things, like limiting the result, trying to get max and min of ranges, I tried around 20 different things and every time same result. Ether is my logic bad or its to much for me to get my had around. Please help.