简体   繁体   中英

join two tables and get only first matching row from second table

I want to join three tables. First table (contacts)contains cid (primary key),name. Second table (familyInfo) contains fid(primary key),cid (fk),contact name and relationID (fk) .Third table(relation type) contains relationID(primary key),relationType like father,mother,brother etc ...

Query should join all rows from first table with first matching row from second table .... Contacts which don't have any relation should display null ....only first matching relation should be shown in result

Please help, Thank you! I have added image of table structures and expected output for better understanding ...please click here for image

You need to use OUTER APPLY

SELECT c.cid,
       c.NAME,
       oa.contact_name
FROM   contacts c
       OUTER APPLY (SELECT TOP 1 f.contact_name
                    FROM   familyInfo f
                    WHERE  c.cid = f.cid
                    ORDER  BY relationID) oa 

How it works

Outer apply will return all the records from left table even thought there is no matching record found in right table

Top 1 with Order by will help you find the first matching row from second table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM