C# 具有多个标记的唯一结果搜索算法

C# 具有多个标记的唯一结果搜索算法,c#,sql,search,C#,Sql,Search,我在SQLServer中有三个表- Photos table: ---------------------- | PhotoId | PhotoName| ---------------------- | | | ---------------------- Tags table: ---------------------- | TagId | TagName| ---------------------- | |

我在SQLServer中有三个表-

Photos table:

----------------------
| PhotoId | PhotoName|
----------------------
|         |          |
----------------------

Tags table:

----------------------
| TagId   |   TagName|
----------------------
|         |          |
----------------------

Junction table:

----------------------
| PhotoId |   TagId  |
----------------------
|         |          |
----------------------
一张照片可以有多个标签,一个标签可以属于多张照片

现在,例如,鹰有标签鸟,动物,野生。我想用标签搜索家畜、鸟类、动物。我使用的是sql语句,其中标记名为“家”或标记名为“鸟”或标记名为“动物”。问题是,当Eagle出现两次时,它会生成查询结果


但我只想要一次鹰。有什么想法吗?

每个照片在结果集中只出现一次

select * from Photos
where PhotoId in
(   select DISTINCT PhotoId
    from Junction
    where TagId in
    (select TagId from Tags where TagName='Domestic' OR TagName='Bird' OR TagName='Animal')
)

使用DISTINCT时,每张照片在结果集中仅显示一次

select * from Photos
where PhotoId in
(   select DISTINCT PhotoId
    from Junction
    where TagId in
    (select TagId from Tags where TagName='Domestic' OR TagName='Bird' OR TagName='Animal')
)

我能想到的最快的解决方案是,你只需要指定照片的名称,然后做一个不同的标记,然后动物的每个名称将根据标记出现一次

SELECT DISTINCT PhotoName
FROM Tags T
JOIN Junction J ON J.TagId = T.TagId
JOIN Photos P ON P.PhotoId = J.PhotoId
WHERE TagName=('Domestic' OR TagName='Bird') OR TagName='Animal'

我能想到的最快的解决方案是,你只需要指定照片的名称,然后做一个不同的标记,然后动物的每个名称将根据标记出现一次

SELECT DISTINCT PhotoName
FROM Tags T
JOIN Junction J ON J.TagId = T.TagId
JOIN Photos P ON P.PhotoId = J.PhotoId
WHERE TagName=('Domestic' OR TagName='Bird') OR TagName='Animal'

有了正确的索引,这可能是最快的解决方案。有了正确的索引,这可能是最快的解决方案。