sql如何判断一个表中的某行是否出现在了另一个表中?

MichealTX 2012-03-14 10:39:13
我想判断表t1中的某行是否出现在了表t2中,如果t1中某行出现在了t2中,则把t1中的这一行和t2中相应的行输出。

t1表内容如下:
col1 col2
a b
b c
g h

t2表如下:
col1 col2 col3
a b i
b d e

这个例子中t1中的第一行出现在了t2中的第一行中,然后输出t1中的第一行和t2中的第一行。可我不会写相应的sql语句。
如果您知道如何解答这个问题,请您给我写出响应的sql语句。谢谢!
...全文
477 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2012-03-14
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 michealtx 的回复:]
您这样就给写死了,我想要个通解。更加灵活的写法。
[/Quote]
你自己组合一下就行了.
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 (...) )
勿勿 2012-03-14
  • 打赏
  • 举报
回复
就把三种情况union all 起来 有三种情况是 第一列和第二和表b相同 也有第一和三 和表b相同 还有就是第二和第三和表b相同 。
  • 打赏
  • 举报
回复

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

*/
MichealTX 2012-03-14
  • 打赏
  • 举报
回复

不能保证一定就是俩表的前两列相同,也许t1中某行的前两列与t2中某行的后两列相同。您这样写就写死了。我想要个更加灵活通用的。

[Quote=引用 3 楼 sqlserver2008 的回复:]

SQL code


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)
[/Quote]
MichealTX 2012-03-14
  • 打赏
  • 举报
回复
首先感谢您的回复。这里有个问题:

因为不能保证一定就是俩表的前两列相同,也许t1中某行的前两列与t2中某行的后两列相同:比如:
t1:
col1 col2
b c

t2:
col1 col2 col3
a b c

您这样就给写死了,我想要个通解。更加灵活的写法。

[Quote=引用 1 楼 dawugui 的回复:]

select t2.* from t2 , t1 where t2.col1 = t1.col1 and t2.col2 = t1.col2
[/Quote]
  • 打赏
  • 举报
回复

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
SqlServer2008 2012-03-14
  • 打赏
  • 举报
回复


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)
dawugui 2012-03-14
  • 打赏
  • 举报
回复
select t2.* from t2 , t1 where t2.col1 = t1.col1 and t2.col2 = t1.col2

select t2.* from t2 where exists(select 1 from t1 where t2.col1 = t1.col1 and t2.col2 = t1.col2 )
dawugui 2012-03-14
  • 打赏
  • 举报
回复
select t2.* from t2 , t1 where t2.col1 = t1.col1 and t2.col2 = t1.col2

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧