Select p.ProductID,
Stuff((Select ','+Cast(ImageID as varchar(10))
From @ProductImages i
Where p.ProductID=i.ProductId
For XML PATH('')
),1,1,''
) as ImageList
From @Products p
Where p.ProductID in (Select ProductID From @ProductImages)
Here are test data I used for this query
Declare @Products Table (ProductID int primary key, ProductName varchar(20))
Declare @ProductImages Table (ProductId int, ImageId int, Primary Key (ProductId, ImageId))
Insert Into @Products
Select 1, 'Product1' Union all
Select 2, 'Product1' Union all
Select 3, 'Product1' Union all
Select 4, 'Product1' Union all
Select 5, 'Product1'
Insert Into @ProductImages
Select 1,1 Union all
Select 1,2 Union all
Select 1,3 Union all
Select 2,4 Union all
Select 2,5 Union all
Select 3,1 Union all
Select 4,3 Union all
Select 4,5
And here is result of query:
ProductID ImageList
--------- ---------
1 1,2,3
2 4,5
3 1
4 3,5
If you want to have ProductID 5 in the list with null for Image list, just remove next line from query:
Where p.ProductID in (Select ProductID From @ProductImages)
You will have one more row in the result (it does not have images assigned):
5 null