I have a 1 to many relation between two tables that I want to combine in a record. Let’s say I have one table called Foo and another table called Bar. Foo contains some content and Bar contains comments to this content. Now I want to list all contents together with the first comment.
This is what I have tried so far:
SELECT T0.[Content], T1.[Comment]
FROM [Foo] I0
INNER JOIN [Bar] T1 ON T1.[ContentCode] = T0.[Code]
That gives me all contents multiple times with many comments. In other words I am saying “Combine all comments with their representing content”. What I am trying to achieve is to say “Only combine one comment with the content”. So I tried this:
SELECT DISTINCT T1.[CommentCode], T0.[Content], T1.[Comment]
FROM [Foo] I0
INNER JOIN [Bar] T1 ON T1.[ContentCode] = T0.[Code]
This works fine. Using ORDER BY I can tell the query to use either the first or the last record found in Bar.
But for some reason DISTINCT is not supported by the database adapter we are forced to use.
Do you face another possibility to limit the results of the right side of the joined relation?
Thanks in advance! 🙂
EDIT:
I am on MSSQL Server 2008 (R2), but accessing it using the SAP Business One DI API. This limits the usage of T-SQL.
A fairly portable way is to query a single comment’s ID in a subquery:
If SQL Server executes the subquery for every row, consider this version instead: