I have 2 tables: ATTACHEMENTS and EMAILS (analogic example). ATTACHEMENTS table holds for each row ReferenceID to email it belongs to. Also I email can have 0 or more attachements.
Tables looks like:
Emails
UID Column1, Column2 ...up to 20 columns
1
2
3
4
Attachements
UID ReferenceID //link to EMAILS.UID
1 2 //this and the one below belong to the same parent.
2 2
3 1
4 3
Now I would need to retrieve all emails with attachement, no matter how many they have.
I need to get all columns so I guess I cannot use distinct, but I need only rows with differente ReferenceID. From the table above, I would need to have result of 3.
In the short: How to select rows with all columns but with distinct referenceID?
Thank you
UPDATE: I removed my previous answer because it is no longer relevant
Ah okay, this should do it. Note that I’m using Microsoft SQL Server table variables for this complete example, just change the select statement to use “Emails” & “Attachements” instead of “@Emails” & “@Attachements” for your tables.
You could also do a DISTINCT with an inner JOIN, though I prefer the style above personally. I’m not sure which is more efficient.
P.S. If the table names are in English, it’s “Attachments” not “Attachements”. If it’s in another language, then ignore me! 🙂