我想判断表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语句。谢谢!
col1 col2
a b
b c
g ht2表如下:
col1 col2 col3
a b i
b d e这个例子中t1中的第一行出现在了t2中的第一行中,然后输出t1中的第一行和t2中的第一行。可我不会写相应的sql语句。
如果您知道如何解答这个问题,请您给我写出响应的sql语句。谢谢!
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
t1:
col1 col2
b ct2:
col1 col2 col3
a b c您这样就给写死了,我想要个通解。更加灵活的写法。
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*/
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 (...) )