【问题标题】:SQL database tag requestSQL 数据库标签请求
【发布时间】:2014-08-17 20:08:57
【问题描述】:

我有一张像这样的照片桌:

id  title      rating  photopath
1   myself     7.0     /photopath1.jpg
2   cat        8.0     /photopath2.jpg
3   dog        6.0     /photopath3.jpg
4   girlfriend 5.0     /photopath4.jpg

还有一个标签表:

id  tag_name   photo_id
1   selfie     1
2   sun        1
3   nature     2
4   relax      2
5   loyal      3
6   journal    3
7   selfie     4
8   sun        4
9   problems   4

我想将所有带有“自拍”和“太阳”标签的照片命名为。我该怎么做?

【问题讨论】:

    标签: sql database tags


    【解决方案1】:

    这是一个“set-within-sets”查询。我喜欢使用聚合和having 来解决这些问题:

    select p.id
    from photos p join
         tags t
         on p.id = t.photo_id
    group by p.id
    having sum(case when tag_name = 'selfie' then 1 else 0 end) > 0 and
           sum(case when tag_name = 'sun' then 1 else 0 end) > 0;
    

    这种方法的方便之处在于可以方便地添加更多条件(如另一个标签)或反转一个条件(如“自拍”没有“太阳”)。

    【讨论】:

      【解决方案2】:
      select p.*
        from photo p
        join (select p.id
                from photo p
                join tag t
                  on p.id = t.photo_id
               where t.tag_name in ('selfie', 'sun')
               group by p.id
              having count(*) = 2) x
          on p.id = x.id
      

      小提琴: http://sqlfiddle.com/#!2/5c95c2/2/0

      输出:

      | ID |      TITLE | RATING |       PHOTOGRAPH |
      |----|------------|--------|------------------|
      |  1 |     myself |      7 | /photograph1.jpg |
      |  4 | girlfriend |      5 | /photograph4.jpg |
      

      【讨论】:

      • IN ('selfie', 'sun') 评估为tag_name = 'selfie' OR tag_name = 'Sun',OP 想要两者都存在的地方。
      • 这就是我使用 HAVING 子句的原因,其中 count 等于 2。这不是我编写它的方式,而是两者兼有。
      • @M.Ali 也许您打算将该评论放在 JammoD 的答案下,即非此即彼
      • 由于您的准确回答和示范,希望给您更多的道具。不过,我将使用 Gordon 的回复,因为正如他所说,正如他所指出的,删除或添加底部查询更多条件会更容易。
      • @AlfonsoFernandez-Ocampo 除非您打算排除 - 并且只搜索包含的标签 - 您对上面所做的唯一事情就是将单词添加到 sql 的第 7 行,和 count(*) 到关键字的总数(而不是添加整个 case 语句),所以我认为它更容易。此外,无论如何您都必须重新加入原始表格才能获得其他字段(标题、评级、照片)
      【解决方案3】:
      SELECT * 
      FROM Photos
      WHERE EXISTS (SELECT 1
                    FROM Tag_Table
                    WHERE photo_id = Photos.id
                     AND tag_name = 'selfie'
                   )
        AND EXISTS (SELECT 1
                    FROM Tag_Table
                    WHERE photo_id = Photos.id
                     AND tag_name = 'Sun'
                   )
      

      【讨论】:

        猜你喜欢
        • 2016-01-08
        • 1970-01-01
        • 2017-01-18
        • 2012-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多