两表多条件关联查询问题

lbd8848 2007-06-08 11:14:25
有两张表,表a,表b
表a:
id unitid photonumber1 photonumber2
===============================================
1 1111
2 12345678
3 22
4 1111
5 12345678
6 11
7
8 12345678

表b:
photonumber unitid
============================
12345678 11
98765441 22
11109101 33

想得到条件unitid包含11的所有表a记录,并包括表a字段unitid为空,但与表b通过photonumber关联,unitid也为11的记录.
查询结果表:

id unitid photonumber1 photonumber2
================================================
1 1111
2 12345678
4 1111
5 12345678
6 11
8 12345678

...全文
268 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
CathySun118 2007-06-08
  • 打赏
  • 举报
回复
select a.* from a
where a.unitid like '%11%' or a.unitid is null
or
exists(select 1 from b where unitid='11' and photonumber in(a.photonumber1,a.photonumber2))
子陌红尘 2007-06-08
  • 打赏
  • 举报
回复
以上示例在SQL Server 2000环境下测试通过,使用了与Oracle通用的语法,Oracle下应该可用。
子陌红尘 2007-06-08
  • 打赏
  • 举报
回复
create table a(id int,unitid varchar(10),photonumber1 varchar(10),photonumber2 varchar(10))
insert into a select 1,'1111',NULL ,NULL
insert into a select 2,NULL ,NULL ,'12345678'
insert into a select 3,'22' ,NULL ,NULL
insert into a select 4,'1111',NULL ,NULL
insert into a select 5,NULL ,'12345678',NULL
insert into a select 6,'11' ,NULL ,NULL
insert into a select 7,NULL ,NULL ,NULL
insert into a select 8,NULL ,'12345678',NULL

create table b(photonumber varchar(10),unitid varchar(10))
insert into b select '12345678','11'
insert into b select '98765441','22'
insert into b select '11109101','33'
go


select
a.*
from
a
where
a.unitid like '%11%'
or
(a.unitid is null
and
exists(select 1 from b where unitid='11' and photonumber in(a.photonumber1,a.photonumber2)))
go

/*
id unitid photonumber1 photonumber2
----------- ---------- ------------ ------------
1 1111 NULL NULL
2 NULL NULL 12345678
4 1111 NULL NULL
5 NULL 12345678 NULL
6 11 NULL NULL
8 NULL 12345678 NULL
*/

drop table a,b
go
jiazheng 2007-06-08
  • 打赏
  • 举报
回复
select * from a
where instr(unitid,'11')>0 or
exists
(select 1 from b where photonumber=a.photonumber1 or photonumber=a.photonumber2 and unitid='11')
這個意思?
icefirelxb 2007-06-08
  • 打赏
  • 举报
回复
没看懂什么意思:(
lixin5678 2007-06-08
  • 打赏
  • 举报
回复
楼上的条件的层次对吗?应该是
select a.* from a
where a.unitid like '%11%' or
(a.unitid is null
and
exists(select 1 from b where unitid='11' and photonumber in(a.photonumber1,a.photonumber2))

libin_ftsafe(子陌红尘:TS for Banking Card)是对的

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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