从左表中选择与右表中的行相关的行

时间:2017-05-31 14:41:43

标签: sql sql-server tsql

给表I:

light.layers.set( 0 ); // don't forget to set the light layers
light.layers.enable( 1 );

mesh.layers.set( 1 );

arrowHelper.traverse( function( node ) { node.layers.set( 1 ); } );

camera.layers.set( 1 );

第二张表C:

I1
I2
I3
I4

第三个CI:

C1
C2
C3

SQL请求的任何想法只给出所有第一个表共有的行,如下面的结果:

I1 C2
I1 C3
I2 C2
I3 C2
I3 C3
I4 C2
I4 C3

对于另一组这样:

C2

结果将为空。

I1 C2
I1 C3
I2 C2
I3 C3
I4 C2
I4 C3

I1
I2
I3
I4
I5

reuslt:空

*参见讨论

谢谢。

4 个答案:

答案 0 :(得分:3)

您可以使用NOT EXISTS

SELECT * 
FROM TableC c
WHERE NOT EXISTS (  SELECT 1 
                    FROM TableI i 
                    WHERE NOT EXISTS (  SELECT 1 FROM TableCI ci 
                                        WHERE   ci.I = i.I 
                                                AND ci.C = c.C
                                     )
                )

GROUP BY, HAVING, COUNT [DISTINCT]作为jarlh的建议

DECLARE @NumberI int = (SELECT count(*) FROM TableI)

SELECT c.C
FROM TableC c
INNER JOIN TableCI ci ON c.C = ci.C
INNER JOIN TableI i ON ci.I = i.I 
GROUP BY c.C
HAVING COUNT(DISTINCT ci.I) = @NumberI

答案 1 :(得分:0)

您可以使用: 在哪里存在(子查询)

答案 2 :(得分:0)

所以,只有当此列中的值与表I中存在的所有记录相关联时,才要显示表CI的第二列?

如果是这样的话,你可以这样做:

select Col2 from  ( select Col2 , count(Col1) As Expr1 from CI group by Col2 ) A
where Expr1 = (select count(*) from I) 

答案 3 :(得分:0)

这是一个简单的解决方案,基本前提是:
我们只想要那些C记录,其I记录的Count Distinct应该与整个表的I记录的Count distinct相同

def bing_search(query):
    AGENT.open('http://www.bing.com/')
    AGENT.select_form(nr=0)
    AGENT.form['q'] = query
    data = AGENT.submit()

在Oracle中,这里是Query和结果集

            select TBL.C, count(distinct TBL.I)
            from TBL
            group by TBL.C
            having count(distinct TBL.I)= (select count(distinct TBL.I) from TBL)

结果集:

           with TBL 
            as
            (
            select 'I1' I,'C2' C from dual
            union all
            select 'I1','C3' from dual
            union all
            select 'I2','C2' from dual
            union all
            select 'I3','C2' from dual
            union all
            select 'I3','C3' from dual
            union all 
            select 'I4','C2' from dual
            union all
            select 'I4','C3' from dual
            )

            select TBL.C, count(distinct TBL.I)
            from TBL
            group by TBL.C
            having count(distinct TBL.I)= (select count(distinct TBL.I) from TBL)