Query XY array pair for y value at arbitrary x in SQL
I'd like to make a database of products. Each product have characteristics
described as an array of x values and corresponding y values. And I'd like
to query products for certain characteristics.
Example product data:
ProductA_x = [10, 20, 30, 40, 50]
ProductA_y = [2, 10, 30, 43, 49]
ProductB_x = [11, 22, 33, 44, 55, 66]
ProductB_y = [13, 20, 42, 35, 28, 21]
Now I'd like to get a list of products where y < 35 @ x=31. In the example
data case, I should get ProductA.
If I use MySQL, what would be a good way to define table(s) to achieve
this query at SQL level?
Would it become easier if I could use PostgreSQL? (Use Array or JSON type??)
One way I was advised was to make a table to specify xy pairs for x range.
First data is for range x[0] to x[1], next data is for x[1] to x[2].
Something like this.
| ProductID | x1 | x2 | y1 | y2 |
| --------- | -- | -- | -- | -- |
| 1 | 10 | 20 | 2 | 10 |
| 1 | 20 | 30 | 10 | 30 |
| 1 | 30 | 40 | 30 | 43 |
| 1 | 40 | 50 | 43 | 49 |
| 2 | 11 | 22 | 33 | 44 |
| 2 | 22 | 33 | 20 | 42 |
| 2 | 33 | 44 | 42 | 35 |
| 2 | 44 | 55 | 35 | 28 |
| 2 | 55 | 66 | 28 | 21 |
Then I could query for (x1 > 31 AND 31 < x2) AND (y1 < 35 OR y2 < 35)
This solution is not too bad but I wonder if there is cleverer approach.
Please note that x array is guaranteed to be incremental but different
product would have different starting x value, step size and number of
points. And x value to be searched for may not exist as exact value in x
array. The length of real x and y arrays would be about 2000. I expect I'd
have about 10,000 products.
It would be best if corresponding y value can be interpolated but
searching y value at nearest x value is acceptable.
No comments:
Post a Comment