日期:2014-05-17  浏览次数:20429 次

如何同时查询2个库的表进行对比?
如何同时查询2个库的表进行对比?
库1:qpqxbs001 表:Card
库2:hyzfzgl   表:NewMemberVisit

目的: 当下面代码查询qpqxbs001库的Card表的数据 查询出来的 card_no列和hyzfzgl库的NewMemberVisit表的card_no列进行对比,如果NewMemberVisit表里面有这个数据就不显示了

说白了就是2个表的数据对比 如果NewMemberVisit有了这条数据就不显示出来了!

现在是单库查询代码

SELECT a.card_no ,a.Card_jlrq ,a.card_kehu_mc ,a.card_kehu_shouji,a.gongsiNo ,a.gongsiMc ,MAX(b.work_no) work_no ,b.xche_ssje ,min(c.wxxm_mc) wxxm_mc FROM qpqxbs001.dbo.Card a LEFT JOIN work_pz_sj b ON a.card_no = b.card_no LEFT JOIN work_mx_sj c ON b.work_no = c.work_no WHERE a.gongsiNo='02' and  a.Card_jlrq >='2014-02-01' and a.Card_jlrq <='2014-02-20'  GROUP BY a.card_no ,a.Card_jlrq , a.card_kehu_mc ,a.card_kehu_shouji ,a.gongsiNo ,a.gongsiMc ,b.xche_ssje ORDER BY card_jlrq DESC

------解决方案--------------------
SELECT a.card_no ,a.Card_jlrq ,a.card_kehu_mc ,a.card_kehu_shouji,
       a.gongsiNo ,a.gongsiMc ,MAX(b.work_no) work_no ,
       b.xche_ssje ,min(c.wxxm_mc) wxxm_mc 
FROM qpqxbs001.dbo.Card a 
LEFT JOIN work_pz_sj b 
       ON a.card_no = b.card_no 
LEFT JOIN work_mx_sj c ON b.work_no = c.work_no 
WHERE a.gongsiNo='02' and  a.Card_jlrq >='2014-02-01' 
and a.Card_jlrq <='2014-02-20'  
and not exists(select 1 from hyzfzgl.dbo.NewMemberVisit n
               where a.card_no = n.card_no)

GROUP BY a.card_no ,a.Card_jlrq ,a.card_kehu_mc ,a.card_kehu_shouji,
         a.gongsiNo,a.gongsiMc ,b.xche_ssje 
ORDER BY card_jlrq DESC