【发布时间】:2022-06-13 21:21:48
【问题描述】:
我正在尝试加入 3 个表,我只需要表 1 中的行,但我得到的记录太多。我想我知道问题出在哪里,但我不知道如何解决。
我有以下表结构,所有 3 个表都必须连接:
InvoiceDetailsTable Columns:
a_invoiceId, a_companyId
InvoiceTable Columns:
b_invoiceId, b_shopId
ShopTable Columns:
c_shopId, c_companyId
在上述情况下,InvoiceTable 中的 invoiceId 不是唯一的。它与 shopId 组合是唯一的。
我有几种情况,其中一个 InvoiceDetail 属于特定 Invoice,但我必须考虑正确的商店...但我在 InvoiceDetails 中没有 shopId...但是我确实有正确的 CompanyId,这应该为了唯一标识InvoiceDetail也要好
我尝试了几个查询,但似乎找不到正确的一个:
select * from invoiceDetailsTable a
left join invoiceTable b on a.invoiceId = b.b_invoiceId
left join ShopTable c on b.b_shopId = c.c_shopId
where a.price is null;
select * from invoiceDetailsTable a
left join invoiceTable b on a.invoiceId = b.b_invoiceId
left join ShopTable c on b.b_shopId = c.c_shopId and a.a_companyId = c.c_companyId
where a.price is null;
不幸的是,当 InvoiceId 属于超过 1 个 shopId/companyId 时,我会收到双重记录。有没有办法解决这个问题?我已经被这个问题困扰了一段时间了。
谢谢!
【问题讨论】:
-
样本数据和预期结果将非常有助于理解此处的实际问题。
-
a等别名代表invoiceDetailsTable和b代表invoiceTable对您或其他想要阅读您的代码的人没有帮助。为您的对象使用有意义且一致的别名;例如,ID用于 发票详细信息,I用于 发票。我建议阅读Bad Habits to Kick : Using table aliases like (a, b, c) or (t1, t2, t3)。
标签: sql sql-server join