简体   繁体   English

如何以一对多关系连接两个表,并且只保留一对一记录?

[英]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 . 我有两个表: FoldersReferences A folder can have 0 to 2 references (usually 1 or 2). 一个文件夹可以有0到2个引用(通常为1或2)。

I have an existing query that search Folders that respect certains conditions. 我有一个现有的查询,搜索尊重某些条件的Folders The query must have a new condition : Find only Folders with one reference. 查询必须具有新条件:仅查找具有一个引用的Folders

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 ). 理想情况下 ,为了限制对此旧应用程序的更改,新条件应仅在WHERE子句内(此规则group by x, having y排除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 输出应该只包含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. 然后使用与临时表join到其他表,并把你想要的条件。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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