SQL使用IN子句选择全部或全部

时间:2013-08-24 13:08:47

标签: sql sqlite

我有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 个答案:

答案 0 :(得分: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');

答案 1 :(得分: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

答案 2 :(得分: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')

答案 3 :(得分: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')))