Following problem:
Query 2 and Query 3 depend on the results of Query 1 and Query 4 depends on the results of query 2. How would you express these queries without executing the same query multiple times?
Example:
Query 1
SELECT id, color, part FROM T1
Query 2
SELECT id, owner FROM T2 WHERE T2.color in (SELECT id, color, part FROM T1)
Query 3
SELECT id from T3 where T3.part in (SELECT id, color, part FROM T1)
Query 4
SELECT id from T4 where T4.owner in (SELECT id, owner FROM T2 WHERE T2.color in (SELECT id, color, part FROM T1))
edit
At the end i need the union of the result
Query1 union Query2 union Query3 union Query4
Now as you can see, I have copied and pasted the previous queries, there must be a better way of doing this.
Do you really need four different result sets? How many rows are you expecting in each set and what kind of entities are T1, T2, T3, T4 – because it may be possible to combine those queries into a single set.
In addition, this:
isn’t valid SQL, you probably mean: