2012-12-14 71 views
2

表的SQL查询:用户ID 名用于连接3个表

表B:ACCID 用户ID ACCNO

表C:的LoanID 用户ID AMT

frnds我嗨, 我想从表A中取顾客的姓名,从表B中选出,并且它们不包括在表c中。 帮我

+6

欢迎来到stackoverflow。你能证明你所尝试过的吗? –

回答

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 

做一个左连接并检查返回的值是空的,检查是否存在是不适合的表A和B的记录表C的纪录。

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 
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) 

这个查询怎么样,这将工作正常我认为