内部连接查询错误结果

时间:2014-02-13 10:57:15

标签: c# sql join sql-server-ce inner-join

您好我正在VS 2010,C#和SQLCe数据库中开发应用程序。

我正在从3个表中分别生成一份报告,分别是收入,经济和交易。

表结构如下:

收入:

Income

Expence:

expence

交易:

trans

为此,我写了查询

select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit], 
i.iAmount as [Credit], t.balance as [Balance] 
from Transactions t 
   inner join Expence e on t.pid=e.pid 
   join Income i on t.pid=i.pid 
where t.pid='11'

但是,当我运行此查询时,我只是

result

我希望我的结果应该像下面的银行对帐单一样。 final

根据我的理解,查询不对。

我们如何编写查询以获得这样的结果?

2 个答案:

答案 0 :(得分:0)

您必须使用left join,而不是使用加入。因为left返回表from中的所有情况,并且案例存在于表Expence e Income中。

select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit], 
    i.iAmount as [Credit], t.balance as [Balance] 
 from Transactions t 
     left join Expence e on t.pid=e.pid 
     left join Income i on t.pid=i.pid 
 where t.pid='11'

答案 1 :(得分:0)

如果我把Expence表中的项目与Transactions表中的项目连接起来是正确的,你应该使用pId和eId并加入来自Income的项目你应该使用pId和iId,所以你的选择看起来像这样:

select t.tDate as [Date], t.tDescription as [Detail],e.eAmount as [Debit], 
i.iAmount as [Credit], t.balance as [Balance] 
from Transactions t 
   inner join Expence e on t.pid=e.pid and t.eId = e.eId
   join Income i on t.pid=i.pid and t.iId = i.iId
where t.pid='11'