sql中.假设有两个表tbl1跟tbl2,表结构完全相同,表里面有一个datetime类型的字段t,我想把两张表同一时间段的行全取出来,可以这样写的:select * from tbl1 where t>datetime1 and t<datetime2 union all select * from tbl2 where t>datetime1 and t<datetime2,  这里的where条件对于两个表都是一样的,但在写程序时,这个条件是在后期才加上去的,即先是有select * from tbl1 union all select * from tbl2, 再加上where t>datetime1 and t<datetime2, 这时, select * from tbl1 union all select * from tbl2 where t>datetime1 and t<datetime2 在sql中执行时where条件只会用于tbl2,而不用于tbl1(在sql测试过了,在access中可能同时用于两个表). 我也想过这样写, select * from tbl1, tbl2  再加上 where t>datetime1 and t<datetime2, 但这时会报错说t不明确. 请问,如何实现这种效果呢?

解决方案 »

  1.   

    --试试
    select * 
    from(
          select * from tbl1 
          union all 
          select * from tbl2 
    ) _x
    where t>datetime1 and t<datetime2
      

  2.   

    谢谢mengmou, 可以啦! 再问一下, 这里的_x是什么意思呢?
      

  3.   

    哦,谢谢,我以前这样写select * from (select .. as _x) where, 哈哈,真菜!