我想判断表t1中的某行是否出现在了表t2中,如果t1中某行出现在了t2中,则把t1中的这一行和t2中相应的行输出。t1表内容如下:
col1 col2
a     b
b     c
g     ht2表如下:
col1 col2 col3
a     b     i
b     d     e这个例子中t1中的第一行出现在了t2中的第一行中,然后输出t1中的第一行和t2中的第一行。可我不会写相应的sql语句。
如果您知道如何解答这个问题,请您给我写出响应的sql语句。谢谢!

解决方案 »

  1.   

    select t2.* from t2 , t1 where t2.col1 = t1.col1 and t2.col2 = t1.col2
      

  2.   

    select t2.* from t2 , t1 where t2.col1 = t1.col1 and t2.col2 = t1.col2select t2.* from t2 where exists(select 1 from t1 where t2.col1 = t1.col1 and t2.col2 = t1.col2 )
      

  3.   

    select * from t1 where exists(select 1 from t2 where t2.col1=t1.col1 and t2.col2=t1.col2)select * from t2 where exists(select 1 from t1 where t1.col1=t2.col1 and t1.col2=t2.col2)
      

  4.   


    select a,b from(
    select t1.col1 as a,t1.col2 as b,t2,col1,t2.col2,t2.col3
    from t1 inner join t2 on t1.col1=t2.col2) a
    union allselect col1,col2 from(
    select t1.col1 as a,t1.col2 as b,t2,col1,t2.col2,t2.col3
    from t1 inner join t2 on t1.col1=t2.col2) b
      

  5.   

    首先感谢您的回复。这里有个问题:因为不能保证一定就是俩表的前两列相同,也许t1中某行的前两列与t2中某行的后两列相同:比如:
    t1:
    col1 col2
    b       ct2:
    col1 col2 col3
    a      b    c您这样就给写死了,我想要个通解。更加灵活的写法。
      

  6.   


    create table t1(
    col1 int,
    col2 int
    )
    insert t1
    select 1,2 union all
    select 2,3 union all
    select 3,4 union all
    select 4,5 union all
    select 5,6 create table t2(
    col1 int,
    col2 int,
    col3 int
    )
    insert t2
    select 1,2,4 union all
    select 2,3,5 union all
    select 5,6,7
    select col1,col2,col3=0 from(
    select t1.col1,t1.col2,t2.col1 as a,t2.col2 as b,t2.col3 as c from t1
    inner join t2 on t1.col1=t2.col1 and t1.col2=t2.col2)m
    union all
    select a,b,c from(
    select t1.col1,t1.col2,t2.col1 as a,t2.col2 as b,t2.col3 as c from t1
    inner join t2 on t1.col1=t2.col1 and t1.col2=t2.col2
    )n/*
    1 2 0
    2 3 0
    5 6 0
    1 2 4
    2 3 5
    5 6 7*/
      

  7.   

    就把三种情况union all 起来 有三种情况是 第一列和第二和表b相同 也有第一和三 和表b相同 还有就是第二和第三和表b相同 。
      

  8.   

    你自己组合一下就行了.
    select t2.* from t2 , t1 where (t2.col1 = t1.col1 and t2.col2 = t1.col2) or ...select t2.* from t2 where exists(select 1 from t1 where (t2.col1 = t1.col1 and t2.col2 = t1.col2) or (...) )