我有一个sql server数据库,里面有两个表, 如下:
表1(4个字段)
ID   xid    Name1  type
1     5       a     x
2     6       b     y
3     7       c     z
表2(三个字段):
ID   xid    Name2
1     5       a2
2     6       b2
3     7       c2
现在我要根据表1的type的值(比如type=x),查询对应表1中的name1字段的值(如a),同时在根据对应的xid的值(如5)到表2中查询对应的Name2字段的值(如a2),然后把表一,表2查到这两个字段的值写到excel表中。
这个查询,需要分两个查询来做呢,还是写一个查询就可以了。

解决方案 »

  1.   

    select t1.*,t2.name2 from t1,t2 where t1.type='x' and t2.xid=t1.xid
      

  2.   

    select t1.name1,t2.name2 from 表1 t1
    left join 表2 t2 on t1.xid=t2.xid
    where t1.type=x
    上面这个语句就是利用left join做连接查询
      

  3.   

    语句中的表1就是第一个表的表名,后面的t1是别名
    表2就是第二个表的表名,同样t2也是别名
    where 条件就是你想查询的Type=X的那条记录
      

  4.   

    select Name2 from t1 left join t2 where type = "x" and t1.xid = t2.xid