1

我有 3 张桌子,其中一张是另外两张之间的地图。给定一个标签列表,我想选择标记可标记的所有其他标签。我会尝试给出我的问题的视觉。

tags
--------------
1 | 'email'
2 | 'gmail'
3 | 'yahoo'
4 | 'hotmail'
5 | 'school'
6 | 'not used'

taggables
--------------------------
1  | 'test1@gmail.com'
2  | 'test2@yahoo.com'
3  | 'test3@hotmail.com'
4  | 'test4@gmail.com'
5  | 'test5@myschool.edu'

tagged
------
1,  1   /* test1@gmail.com   --> email */
1,  2   /* test1@gmail.com   --> gmail */
2,  1   /* test2@yahoo.com   --> email */
2,  3   /* test2@yahoo.com   --> yahoo */
3,  1   /* test3@hotmail.com --> email */
3,  4   /* test3@hotmail.com --> hotmail */
4,  1   /* test4@gmail.com   --> email */
4,  2   /* test4@gmail.com   --> gmail */
5,  1   /* test5@myschool.edu--> email */
5,  5   /* test5@myschool.edu--> school */

所以给出'email', 'gmail'的结果集列表应该是'yahoo', 'hotmail', 'school'. 我在这方面花了太多时间,可以使用一些帮助。

4

4 回答 4

1

这种方法获取所有带有您想要的标签的项目。然后它in用于查找这些项目上的所有标签。如果我正确理解您的问题,这就是您所要求的:

select distinct td.*
from tagged td join
     tags t
     on td.tagid = t.tagid
where td.itemid in (select itemid
                    from tagged td join
                         tags t
                         on td.tagid = t.tagid
                    where t.tagname in ('gmail', 'email')
                   ) and
      t.tagname not in ('gmail', 'email');
于 2013-08-24T13:15:13.843 回答
0
SELECT DISTINCT T.tagname
FROM tags T
  JOIN tagged TT
    ON T.id = TT.tagID -- getting only used tags
  LEFT JOIN taggables TG
    ON TT.taggabeId = TG.ID
WHERE TG.id IS NULL        -- getting unassigned tags
  AND T.tagname IN ('gmail', 'email')  -- filtering by given confition
于 2013-08-24T13:17:43.503 回答
0

一种方法是将公用表连接到自身 - 左列(带有 tagIds)连接到右列(带有 taggableIds)

Select distinct t.TagName  
From tags t
    join tagged d On d.tagId = t.TagId
    join tagged d2 On d2.taggAbleId = d.taggAbleId 
where d2.tagId in (1,2)
    and d2.tagid Not in (1,2) 

或者如果您想使用字符串名称进行谓词,请再加入一个

Select distinct t.TagName  
From tags t
    join tagged d On d.tagId = t.TagId
    join tagged d2 On d2.taggAbleId = d.taggAbleId 
    join tags t2 On t2.tagId = d2.TagId
where t2.tagName in ('gmail', 'email')
    and t2.tagtName Not in ('gmail', 'email')
于 2013-08-24T13:35:47.963 回答
0
SELECT * FROM tags WHERE name NOT IN ('email', 'gmail')

SELECT * FROM taggables 
WHERE ID IN (SELECT ID FROM tagged WHERE id_tag IN (SELECT id FROM tags WHERE name NOT IN ('email', 'gmail')))
于 2013-08-24T14:11:17.493 回答