日期:2014-05-18  浏览次数:20523 次

求助:两张表的联合查询
表A:
select   语句如下:
select   id,datatime,z,wt,q   from   A   where   datediff(hh,datatime,getdate())=0   and   id   in(select   id   from   C)
查询结果如下:
ID     datatime                           z       wt     q
1     2012-05-04   21:00:000   123   23.5   234
2     2012-05-04   21:00:000   134   45.6   456
3     2012-05-04   21:00:000   345   89.0   987
4     2012-05-04   21:00:000   445   89.0   787
5     2012-05-04   21:00:000   365   39.0   287
6     2012-05-04   21:00:000   765   89.0   787
7     2012-05-04   21:00:000   145   59.0   677
8     ......
9......
....
15     2012-05-04   21:00:000   645   89.0   987
表A查询的结果是上面的15条数据。
----------------------------------
表B:
select   语句如下:
select   id,datatime,tt   from   B   where   datediff(hh,datatime,getdate())=0   and   id   in(select   id   from   C)
查询结果如下;
ID     datatime                         tt
1     2012-05-04   21:00:000   0.5
2     2012-05-04   21:00:000   1

4     2012-05-04   21:00:000   1.5
5     2012-05-04   21:00:000   3

7     2012-05-04   21:00:000   2.5
8     ......
9......
....
15     2012-05-04   21:00:000   1
------------------------------------------------------
表A和表B中的ID都是从表C中来的,表B的查询结果比表A少了两条,就是ID=3和ID=6的没有,我现在要得到如下的结果:
ID         atatiem                         z       wt       q         tt
1     2012-05-04   21:00:000   123   23.5   234       0.5
2     2012-05-04   21:00:000   134   45.6   456         1
3     2012-05-04   21:00:000   345   89.0   987       null
4     2012-05-04   21:00:000   445   89.0   787         1.5
5     2012-05-04   21:00:000   365   39.0   287         3
6     2012-05-04   21:00:000   765   89.0   787         null
7     2012-05-04   21:00:000   145   59.0   677         2.5
8     ......
9     ......
10
11
12
13
14   ....
15     2012-05-04   21:00:000   645   89.0   987       2.5
我写的select   语句如下:
select   a.id   ,a.datatime,a.z   ,a.wt,a.q,b,tt   from   A   a,B   b
where   a.id=b.id   and   datediff(hh,a.datatime,getdate())=0
and   a.id   in   (select   STCD   from   C)   and   a.tm=b.tm
order   by   a.stcd
得到的结果也是没有ID=3和ID=6的数据,请问这个语句该怎么写?


------解决方案--------------------
select a.id ,a.datati