简体   繁体   中英

How to join two tables in a one-to-many relation, and keep only one-to-one records?

I have two tables : Folders and References . A folder can have 0 to 2 references (usually 1 or 2).

I have an existing query that search Folders that respect certains conditions. The query must have a new condition : Find only Folders with one reference.

Ideally , to limits change to this old application, the new condition should be within the WHERE clause only (This rule out group by x, having y ).

Ex :

FolderId Name
0        Folder0
1        Folder1
2        Folder2

RefId FolderId Name
0     1        ref1
1     2        ref2
2     2        ref3

The output should only contain the FolderId 1

Use the query below to create a temporary table or create a table variable:

create table #Temp
(
    column_name int
)

insert into #Temp
     SELECT column_name
      FROM table_name
     GROUP BY column_name
    HAVING COUNT(column_name) = 1;

Then use the temp table with join to other tables and place the conditions you want.

You probably want this:

select . . .
from folders f join
     (select r.*, count(*) over (partition by folderid) as cnt
      from references r
     ) r
     on f.folderid = r.folderid and cnt = 1;

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