D
D
Dmitry2022-02-12 17:55:08
SQL Server
Dmitry, 2022-02-12 17:55:08

What can cause a row to repeat when joining multiple tables?

use PhonesShop
declare @SettingForFilter date
set @SettingForFilter = '2021-10-12'
select distinct *
from Orders LEFT JOIN Customers on Orders.CustomerCode = Customers.CustomerCode 
LEFT JOIN Accessories on Orders.AccessorieCode1 = Accessories.AccessorieCode or Orders.AccessorieCode2 = Accessories.AccessorieCode or Orders.AccessorieCode3 = Accessories.AccessorieCode 
LEFT JOIN Services on Orders.ServiceCode1 = Services.ServiceCode or Orders.ServiceCode2 = Services.ServiceCode or Orders.ServiceCode3 = Services.ServiceCode
LEFT JOIN Workers on Orders.WorkerCode = Workers.WorkerCode
where Orders.OrderDate = @SettingForFilter

I can't understand why I get a duplicate (as many as 18 identical lines)6207ca484eea7559742500.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Tsvetkov, 2022-02-12
@roflanPominki

LEFT JOIN Accessories on Orders.AccessorieCode1 = Accessories.AccessorieCode 
  OR Orders.AccessorieCode2 = Accessories.AccessorieCode 
  OR Orders.AccessorieCode3 = Accessories.AccessorieCode
This connection is repeated 3 times (for each field).
LEFT JOIN Services on Orders.ServiceCode1 = Services.ServiceCode 
 OR Orders.ServiceCode2 = Services.ServiceCode 
 OR Orders.ServiceCode3 = Services.ServiceCode
And 3 more times. Already 3 * 3 = 9 times, for example, the first lines.
Therefore, you need to bind each field separately:
SELECT *
  FROM Orders 
    LEFT OUTER JOIN Accessories AS A1 ON Orders.AccessorieCode1 = A1.AccessorieCode 
    LEFT OUTER JOIN Accessories AS A2 ON Orders.AccessorieCode2 = A2.AccessorieCode
    LEFT OUTER JOIN Accessories AS A3 ON Orders.AccessorieCode3 = A3.AccessorieCode

D
Dimonchik, 2022-02-12
@dimonchik2013

you need to firmly remember that
JOIN
is a Cartesian product
i.e. with your 4 JOIN combinations there will be 2 in the cube
, and already all sorts of WHEREs thin it out and discard unsatisfactory elements

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question