我现在有一张表,上面每一行是一个ID,和ID的一种分类:Tag,每个ID可能会有很多个Tag,所以可能出现在很多行。现在希望查询到既拥有 Tag1,Tag2,Tag3...TagN的favorID集合,如果是只有两个ID的话,用一次inner join就可以了。就像:
Select row1 from table
Select row2 from talbe
where row1.Tag == Tag1 && row2.Tag == Tag2 && row1.ID == row2.ID
select row;以上是两个tag的情况,如果是三个tag得这样:
Select row1 from table
Select row2 from talbe
Select row3 from talbe
where row1.Tag == Tag1 && row2.Tag == Tag2 && row3.Tag == Tag3 && row1.ID == row2.ID && row2.ID == row3.ID
select row;所以tag的数目是变量,这个linq语句也会不同,不知道有什么办法可以处理,主要是不太了解linq语句的一些语法特性。 

解决方案 »

  1.   

    如果楼主的目的是想查询包含所有Tag的ID
    SQL查询为select id
    from table  a
    where not exists (select * from table b
                      where not exists (select * from table c
                                        where c.id=a.id and c.id=b.id))
      

  2.   

    改下select id
    from table  a
    where not exists (select * from table b
                      where not exists (select * from table c
                                        where c.id=a.id and c.Tag=b.Tag))
      

  3.   

    我的目的不是想查询包含所有tag的id,而是包含所有指定tag的id
      

  4.   

    那就把c表改为(select * from  table where Tag in(Tag1,Tag2,Tag3))C
      

  5.   


    每一行只有一个tag,同一个id对应有很多行
      

  6.   

    用and连接select  * from tab a where exists(select * from tab where (id=a.id and tag=tag1) and (id=a.id and tag=tag1)  and ....)
      

  7.   

    select * from tab where (id=a.id and tag=tag1) and (id=a.id and tag=tag1)  and ....这样写不知道行不行呢,每次是返回(id=a.id and tag=tag1) and (id=a.id and tag=tag2)这个条件是属于不同的两行的哦