从内连接中的2个表中获取数据

时间:2017-11-13 18:35:12

标签: sql join inner-join

我不是内连接的新手,但我不知道为什么我从两个表中获取数据

看,我有一些表

表一

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionD 
  

TransactionMId ModelNumber EmeiNo Color

     

c174f2c0-72f4-4746-b83d-21ffca6a5a61 620G 10001灰色

     

c174f2c0-72f4-4746-b83d-21ffca6a5a61 ONE 10005 black

     

4fa11531-886a-4d15-af5c-7355cc3648f5 620G 10001灰色

表二

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionP
  

TransactionMId ModelNumber EmeiNo Color

     

c174f2c0-72f4-4746-b83d-21ffca6a5a61 620G 10001灰色

     

c174f2c0-72f4-4746-b83d-21ffca6a5a61 ONE 10005 black

表三

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionS
  

TransactionMId ModelNumber EmeiNo Color

     

4fa11531-886a-4d15-af5c-7355cc3648f5 620G 10001灰色

现在我想显示表1和表2中的数据,但不是表3中的数据

这是我的内部联接

SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
INNER JOIN dbo.tblTransactionS AS TS
ON
TP.EmeiNo != TS.EmeiNo

但执行的结果显示了这样的数据

BrandId Color   EmeiNo
1   grey    10001
1   black   10005

10001的记录不应该在查询中显示,因为它在表3中

我的内部联接有什么问题

2 个答案:

答案 0 :(得分:1)

以下查询将起作用:

SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
where TP.EmeiNo not in (select distinct EmeiNo from dbo.tblTransactionS);

答案 1 :(得分:0)

如果我理解你的问题,你可以这样试试;

SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON TP.transactionMId=TD.transactionMId
where TP.EmeiNo not in (select distinct EmeiNo from dbo.tblTransactionS);

根据您的说明 tblTransactionS (三个表),无需加入