我有3个表。 master, consumer&charge. InvoiceID 是 master 的 PK,存在于 Consumer&Charge 表中。 Consumer PK是ConsumerID和InvoiceID。 charge PK是Charge ID,Fk是Consumer ID。我正在尝试显示所有表中的列,但是某些消费者ID在显示时没有显示,因为费用表中没有引用它的行。我尝试进行左连接,但仍然不显示。有什么建议吗?
编辑:
所以我已经弄清楚了如何做一个左连接,但是如果对于 3 张桌子,我该怎么做?我可以在没有负责人条目的地方显示消费者ID,但在没有消费者条目的地方无法获得发票ID。主人可能有也可能没有消费者,消费者可能有也可能没有收费。.
var query = from m in IM.GetMaster()
join co in CM.GetConsumers()
on m.InvoiceId equals co.InvoiceId
join ch in CCM.GetCharge()
on new { co.InvoiceId, co.ConsumerId }
equals new { ch.InvoiceId, ch.ConsumerId } into temp
from ch in temp.DefaultIfEmpty()
select new {
InvioceID = m.InvoiceId,
ConsumerID = co == null? 0 : co.ConsumerId,
ChargeID = ch == null ? 0 : ch.ChargeId,
Amount = ch == null ? 0 : ch.Amount
};
客户表应该在顶部。查看这篇关于left join
和这篇文章的帖子。
var query = from ConsumerEntity in consumer
join MasterEntityConsumerEntity in master
on ConsumerEntity.InvoiceId equals MasterEntity.InvoiceId
into tmp in MasterEntityConsumerEntity from tmp.DefaultIfEmpty()
join ConsumerChargeEntity in charge
on new { ConsumerEntity.InvoiceId, ConsumerEntity.ConsumerId }
equals new { ConsumerChargeEntity.InvoiceId, ConsumerChargeEntity.ConsumerId }
into ctmp in ConsumerChargeEntity from ctmp.DefaultIfEmpty()
select new
{
InvoiceID = MasterEntity.InvoiceId,
ConsumerID = ConsumerEntity.ConsumerId,
ChargeID = ConsumerChargeEntity.ChargeId,
Amount = ConsumerChargeEntity.Amount,
};
更新
你几乎接近了。
您的查询 : 1 INNER JOIN 2
和 2 LEFT JOIN 3
以下查询:1 LEFT JOIN 2
和2 LEFT JOIN 3
var query = from m in IM.GetMaster()
join co in CM.GetConsumers()
on m.InvoiceId equals co.InvoiceId into tempCo
from co in tempCo.DefaultIfEmpty()
join ch in CCM.GetCharge() on
new { co.InvoiceId, co.ConsumerId } equals
new { ch.InvoiceId, ch.ConsumerId } into temp
from ch in temp.DefaultIfEmpty()
select new
{
InvioceID = m.InvoiceId,
ConsumerID = co == null? 0 : co.ConsumerId,
ChargeID = ch == null ? 0 : ch.ChargeId,
Amount = ch == null ? 0 : ch.Amount
};