27,579
社区成员
发帖
与我相关
我的任务
分享
-->SQL2000的方法(借助辅助字段方法)
alter table 表1 add px int identity --增加辅助字段
select a.*,b.[IDCardNo],b.[name] --开始查询
from 表2 a
left join 表1 b
on a.[PlaceID]=b.px
alter table 表1 drop column px --删除辅助字段
/*
PlaceID Place IDCardNo name
----------- ---------- ---------- ----------
1 USA xxxabc bill
2 U.K xxxabc paul
3 CHN NULL NULL
(3 行受影响)
if object_id('表2') is not null
drop table 表2
go
create table 表2([PlaceID] int,[Place] varchar(10))
insert 表2 select '1','USA'
insert 表2 select '2','U.K'
insert 表2 select '3','CHN'
go
if object_id('表1') is not null
drop table 表1
go
create table 表1([IDCardNo] varchar(10),[name] varchar(10))
insert 表1 select 'xxxabc','bill'
insert 表1 select 'xxxabc','paul'
go
-->SQL2005的方法
select a.*,b.[IDCardNo],b.[name]
from 表2 a
left join (select *,px=row_number() over(order by getdate()) from 表1) b
on a.[PlaceID]=b.px
/*
PlaceID Place IDCardNo name
----------- ---------- ---------- ----------
1 USA xxxabc bill
2 U.K xxxabc paul
3 CHN NULL NULL
(3 行受影响)
*/
-->SQL2000的方法(借助临时表)
select px=identity(int,1,1),* into # from 表1
select a.*,b.[IDCardNo],b.[name]
from 表2 a
left join # b
on a.[PlaceID]=b.px
drop table #
/*
PlaceID Place IDCardNo name
----------- ---------- ---------- ----------
1 USA xxxabc bill
2 U.K xxxabc paul
3 CHN NULL NULL
(3 行受影响)
*/
if object_id('表2') is not null
drop table 表2
go
create table 表2([PlaceID] int,[Place] varchar(10))
insert 表2 select '1','USA'
insert 表2 select '2','U.K'
insert 表2 select '3','CHN'
go
if object_id('表1') is not null
drop table 表1
go
create table 表1([ID] varchar(10),[name] varchar(10))
insert 表1 select 'xxx001','bill'
insert 表1 select 'xxx002','paul'
go
select a.*,b.* from 表2 a left join 表1 b on a.placeID=right(b.id,3)*1
/*
PlaceID Place ID name
----------- ---------- ---------- ----------
1 USA xxx001 bill
2 U.K xxx002 paul
3 CHN NULL NULL
(3 行受影响)
*/
这样可以吗?if object_id('表2') is not null
drop table 表2
go
create table 表2([PlaceID] int,[Place] varchar(10))
insert 表2 select '1','USA'
insert 表2 select '2','U.K'
insert 表2 select '3','CHN'
go
if object_id('表1') is not null
drop table 表1
go
create table 表1([ID] int,[name] varchar(10))
insert 表1 select '3','bill'
insert 表1 select '4','paul'
go
select a.*,b.* from 表2 a left join 表1 b on a.placeID=b.id-2
/*
PlaceID Place ID name
----------- ---------- ----------- ----------
1 USA 3 bill
2 U.K 4 paul
3 CHN NULL NULL
(3 行受影响)
*/
select a.*,b.* from 表2 a left join 表1 b on a.placeID=b.id-2