日期:2014-05-19  浏览次数:20532 次

====谁帮忙看一下这个SQL语句怎么写?====
有两个表:UserClass和UserFile,数据分别如下:
UserClass:
userClassID   userID   userClassNo
---------------------------------------
1      1   0001
2      1   00010001
3      1   000100010001
4      1   000100010002
5      1   000100010003
6      1   00010002
7      1   000100020001
8      1   000100020002
9      2   00010002
10        2   000100020001
11        2   000100020002

UserFile:
userFileID   userID   userClassNo
---------------------------------------------
1      1   000100020002
2      2   000100020001

现在我想根据UserFile表,获得UserClass表的记录集合,关键是两个表userID相同,然后UserClass中显示包含UserFile的所有父分类,即:
返回UserClass:
userClassID   userID   userClassNo
---------------------------------------
1      1   0001
6      1   00010002
8      1   000100020002
9      2   00010002
10        2   000100020001

这样的语句怎么写?分不够再加啊~~~

------解决方案--------------------
select * from UserClass a
where exists (
select 1 from UserFile b
where b.userID=a.userID
and b.userClassNo like rtrim(userClassNo)+ '% '
)


------解决方案--------------------
如果你的編碼是這樣的規律的話,可以這麼寫

Select A.*
From UserClass A
Inner Join UserFile B
On A.userID = B.userID And B.userClassNo Like '% ' + A.userClassNo + '% '
------解决方案--------------------
--创建测试环境
create table UserClass(userClassID int,userID int,userClassNo varchar(50))
create table UserFile(userFileID int,userID int,userClassNo varchar(50))


--插入测试数据
insert UserClass(userClassID,userID,userClassNo)
select '1 ', '1 ', '0001 ' union all
select '2 ', '1 ', '00010001 ' union all
select '3 ', '1 ', '000100010001 ' union all
select '4 ', '1 ', '000100010002 ' union all
select '5 ', '1 ', '000100010003 ' union all
select '6 ', '1 ', '00010002 ' union all
select '7 ', '1 ', '000100020001 ' union all
select '8 ', '1 ', '000100020002 ' union all
select '9 ', '2 ', '00010002 ' union all
select '10 ', '2 ', '000100020001 ' union all
select '11 ', '2 ', '000100020002 '

insert UserFile(userFileID,userID,userClassNo)
select '1 ', '1 ', '000100020002 ' union all
select '2 ', '2 ', '000100020001 '

--求解过程
Select _uc.*
From UserClass _uc
Join UserFile _uf
On _uc.userID = _uf.userID And _uf.userClassNo Like _uc.userClassNo + '% '


--删除测试环境
drop table UserClass
drop table UserFile
/*--测试结果
userClassID userID userClassNo
----------- ----------- --------------------------------------------------
1 1 0001
6 1 00010002
8 1 000100020002
9 2 00010002
10 2 000100020001

(所影响的行数为 5 行)
*/