在写比较复杂的sql查询语句时,涉及到一个或多个select的语句,作为另外一个select语句的查询条件的情况时,如果一下子写不出来,可以利用with关键字,生成一个临时的表,然后在基于这个临时的表进行查询,这样,就减少了select语句的嵌套,同时也降低了难度。如下所示:
with temp1 as (select * from table1 where item1='item1' and item2='item2')
select * from temp1, table2 where temp1.item1=table2.itemx
With关键字后面建立多个sql子句创建的临时表,分别以逗号分开即可,如下所示:
With table1 as (select ...),
table2 as (select...),
table3 as (select...),
select table1.item1, table2.item2, table3.item3 from table1, table2, table3 where xxx