SQL Queries: Queries depending on previous queries and merging results
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.
Just join them by the specific columns.
select * from T1
inner join T2 on T1.color=T2.color
inner join T3 on T3.part=T1.part
inner join T4 on T4.owner=T2.owner
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:
SELECT id, owner FROM T2 WHERE T2.color in (SELECT id, color, part FROM T1)
isn't valid SQL, you probably mean:
SELECT id, owner FROM T2 WHERE T2.color in (SELECT color FROM T1)
精彩评论