I have 3 tables; A with 10000 rows, B with 392540 rows, and C with 200189 rows.
If i query it like this,
SELECT * FROM A a
LEFT JOIN B b
ON b.Id = a.Id
I will have the result in a minute. Also, if i query like this,
SELECT * FROM A a
CROSS APPLY(SELECT *
FROM C c
WHERE c.Id = a.Id
) com
It also returns the data in a minute or less. But when i combine the three,
SELECT * FROM A a
LEFT JOIN B b
ON b.Id = a.Id
CROSS APPLY (SELECT *
FROM C c
WHERE c.Id = a.Id
) com
The query is still running after 30 mins. Note that i used CROSS APPLY instead of INNER JOIN because INNER JOIN takes much longer. I already tried replacing the LEFT JOIN with an OUTER APPLY but nothing seems to work. Can someone suggest a better way to join these tables? Thanks.
EDIT Tables are provided by clients. I added logic to table B only. For A and C, i get it directly from tables they provided. Here is what i did to table B
DECLARE @B AS TABLE(
[Id] nvarchar(max)
, [Name] nvarchar(max)
, [ProductId] nvarchar(max)
, [ProductName] nvarchar(max)
)
INSERT INTO @B
SELECT
a.[Id]
, a.[Name]
, a.[ProductId]
, a.[ProductName]
FROM ( SELECT
[Id]
, [Name]
, [ProductId]
, [ProductName]
, ROW_NUMBER() OVER(PARTITION BY [Id] ORDER BY [Name] DESC) num
FROM tableBbyClient
WHERE [Description] = 'AS'
) a
WHERE a.num=1