【问题标题】:Search algorithm for unique result with multiple tags具有多个标签的唯一结果的搜索算法
【发布时间】:2015-03-31 10:02:54
【问题描述】:

我在sql server中有三个表-

Photos table:

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

Tags table:

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

Junction table:

----------------------
| PhotoId |   TagId  |
----------------------
|         |          |
----------------------

一张照片可以有多个标签,一个标签可以属于多张照片。

现在,例如 Eagle 有标签 Bird, Animal, Wild。我想使用标签Domestic, Bird, Animal 进行搜索。我正在使用 sql 语句where TagName='Domestic' OR TagName='Bird' OR TagName='Animal'。问题是,它会在 Eagle 出现两次的地方产生查询结果。

但我只想拥有一次 Eagle。有什么想法吗?

【问题讨论】:

    标签: c# sql search


    【解决方案1】:
    SELECT p.*
    FROM photos p
    WHERE EXISTS ( SELECT 'a'
                   FROM junction j
                   JOIN tags t ON t.TagId = j.TagId
                   WHERE p.PhotoId = j.PhotoId
                   AND t.TagName IN ('Domestic', 'Bird', 'Animal')
                  )
    

    【讨论】:

    • 有了正确的索引,这可能是最快的解决方案。
    【解决方案2】:
    select distinct p.*
    from photos p
    inner join Junction j on j.PhotoId = p.PhotoId
    inner join tags t on j.TagId = t.TagId
    where t.TagName in ('Domestic', 'Bird','Animal')
    

    【讨论】:

      【解决方案3】:

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

      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'
      

      【讨论】:

        【解决方案4】:

        使用 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')
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-06
          相关资源
          最近更新 更多