Share via

Left Join Issue

Johnathan Simpson 586 Reputation points
2022-05-10T18:00:33.94+00:00

I've got a 1 to many relationship between two tables. I thought a Left join would give me 1 row, but it's giving me all the rows! Should I do Select Top 1? I'm wanting as many rows that exist in ui to be returned from my query, not the opposite, and have the data from ui returned for each row in data

Create Table ui
(
 ID int IDENTITY(1,1) PRIMARY KEY,
 username varchar(500),
 fileid varchar(max)
)

Create Table data
(
  ID int IDENTITY(1,1) PRIMARY KEY,
  fileid varchar(max)
)

Insert Into ui (username, fileid) Values ('abc-123', '1.xlsx'), ('lmn-123', '2.xlsx')
Insert Into data (fileid) Values ('1.xlsx'), ('1.xlsx'), ('1.xlsx'), ('1.xlsx'), ('1.xlsx'), 
('1.xlsx'), ('1.xlsx'), ('1.xlsx'), ('1.xlsx'), ('1.xlsx'), 
('1.xlsx'), ('1.xlsx'), ('1.xlsx'), ('1.xlsx'), ('1.xlsx'), 
('1.xlsx'), ('1.xlsx'), ('2.xlsx')

Select ui.*
FROM ui
left join data 
on ui.fileid = data.fileid
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Naomi Nosonovsky 8,906 Reputation points
2022-05-10T18:10:42.017+00:00

If you need only 1 row from data to match 1 row from ui, then you need to use OUTER APPLY and select top (1) approach and order by some column, say, ID, e.g.

select ui.*, d.*
from ui
OUTER APPLY (select top (1) * from data d where d.FileId = ui.FileId order by d.Id) D

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.