用于连接3个表的SQL查询

时间:2012-12-14 08:21:42

标签: sql-server-2008

表A:用户ID          名称

表B:accid          用户身份          ACCNO

表c:loanid          用户身份          AMT

嗨frnds, 我想从表A中获取客户名称,从表B中获取accno,并且它们不包括在表c中。 帮助我

3 个答案:

答案 0 :(得分:2)

SELECT a.name, b.accno
FROM a inner join b on b.userid = a.userid
where a.userid not in (select distinct userid from c)

这个查询怎么样我会认为这很好用

答案 1 :(得分:1)

尝试:

SELECT a.name, b.accno
FROM tableA a 
JOIN tableB b on a.userid = b.userid
LEFT JOIN tableC c on a.userid = c.userid
WHERE c.userid IS NULL

执行左连接并检查返回的值是否为空,检查表c中是否有记录表a和b中的记录。

答案 2 :(得分:1)

解决方案1:

;with cte as
(Select a.name,b.accno,a.userid
from tableA a
join tableB b
on a.userid = b.userid)

select x.name,x.accno
from cte x 
where x.userid not in (select userid from tableC)

解决方案2:

;with cte as
(Select a.name,b.accno,a.userid
from tableA a join tableB b 
on a.userid = b.userid)
select x.name,x.accno
from cte x 
where x.userid in(select c.userid 
                 from cte c 
                 except 
                 select tc.userid 
                from tableC tc)

解决方案3

;with cte as
(Select a.name,b.accno,a.userid
from tableA a join tableB b 
on a.userid = b.userid)

select x.name,x.accno
from cte x
left join tableC tc
on x.userid = tc.userid
where tc.userid is null