I'm trying to join 3 tables where I only need the rows from table 1 but I'm getting too many records.
I have the following table structure and all 3 tables must be joined:
InvoiceDetailsTable Columns:
IDE_invoiceId, IDE_companyId, IDE_InvoiceDetailsId, IDE_price etc...
---data=>
InvoiceId1, companyId1
....
InvoiceId1001, companyId1
InvoiceId1001, companyId2
InvoiceTable Columns:
I_invoiceId, I_shopId
---data=>
InvoiceId1, shopId1
...
InvoiceId1001, shopId5
InvoiceId1001, shopId6
ShopTable Columns:
S_shopId, S_companyId
--data=>
shopId5, companyId1
shopId6, companyId2
....
In the above situation the invoiceId in InvoiceTable is not unique. It is unique in combination with the shopId.
I have several cases where one InvoiceDetail belongs to a specific Invoice but I must take in account the correct shop. But I don't have the shopId in InvoiceDetails. I do however have the correct CompanyId and this should be good too in order to uniquely identify the InvoiceDetail.
I have tried several queries but can't seem to find a correct one:
select * from invoiceDetailsTable IDE where IDE_price is null;
The above query returns 3 records.
The query below returns 5 records because of the same InvoiceId 'InvoiceId1001'.
select * from invoiceDetailsTable IDE
left join invoiceTable I on IDE.IDE_invoiceId = I.I_invoiceId
left join ShopTable S on I.I_shopId = S.S_shopId
where IDE.IDE_price is null;
select * from invoiceDetailsTable IDE
left join invoiceTable I on IDE.IDE_invoiceId = I.I_invoiceId
left join ShopTable S on I.I_shopId = S.S_shopId and IDE.IDE_companyId = S.S_companyId
where IDE.IDE_price is null;
Unfortunately I'm getting double records when an InvoiceId belongs to more then 1 shopId/companyId. How to solve this?