MySQL complex nested query creating a view
-
19-06-2021 - |
Question
I would like to create a view from a table like this:
Configuration | Size | Runtime
0 | 10 | 32.5
1 | 10 | 30.8
2 | 10 | 40.1
0 | 20 | 61.0
1 | 20 | 65.3
2 | 20 | 56.8
Where configuration number 0 is special (it is the default configuration) and it is present in every group of "Size" values. My goal is to create a view like this:
Configuration | Size | Speedup
0 | 10 | 1.0
1 | 10 | 1.05
2 | 10 | 0.81
0 | 20 | 1.0
1 | 20 | 0.93
2 | 20 | 1.07
For each group of rows with the same size I would like to find the default configuration (identified by number 0) and then compute the ratio between the runtime of the considered row and the default runtime.
This can be splitted in two queries:
- look for the default runtime for the given "Size"
- perform the ratio between the runtime and the default.
The problem is that in query number 1 (that should be a subquery in the select statement of query 2) I don't know which "Size" I am currently considering. I hope you understand what I mean.
I there a way around this problem ?
Solution
Another approach you could use is a subselect:
CREATE VIEW yourview AS
SELECT
Configuration,
Size,
(SELECT Runtime
FROM yourtable AS T2
WHERE T1.Size = T2.Size
AND T2.Configuration = 0) / Runtime AS SpeedUp
FROM yourtable AS T1
See it working online: sqlfiddle
OTHER TIPS
SELECT Configuration, Size, default.Runtime / t.Runtime AS Speedup FROM t JOIN (
SELECT Size, Runtime FROM t WHERE Configuration = 0
) `default` USING (Size)
See it on sqlfiddle.