求一个筛选数据的方法

leisang 2010-06-01 02:51:06
我有一个公交路线表A,存储的公交路线大概如下:
1
2
3
4
5
10
110
101

现在有另个表B,存储了某房产涉及的公交路线,大概如下:
编号: 公交路线
10001 1,101
10002 10,110

然后我想输入比如10,就能得到10路公交所经过的所有内容,如果用like,则会将110之类的都搜出来,请问如何解决?



...全文
112 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
leisang 2010-06-01
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 wlmstar 的回复:]
个人感觉可以先用like,然后对like 后的结果再用charindex,我想,应该快一些。[/Quote]

唉,头疼啊,存储过程里用like,前台代码再筛选一次速度会比较快,但这样一来记录总数就不对了,我这个又是个分页程序。
wlmstar 2010-06-01
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 leisang 的回复:]

引用 1 楼 xys_777 的回复:
SQL code
declare @s varchar(10)
set @s='10'

select * from tb where charindex(','+@s+',',','+公交路线+',')>0


测试过了,确实可以用,但是用了charindex后速度慢的不行,十万条的数据,扔到网站上基本查不动啊。。。
[/Quote]
个人感觉可以先用like,然后对like 后的结果再用charindex,我想,应该快一些。
jaydom 2010-06-01
  • 打赏
  • 举报
回复

create table ta ( num varchar(10) )
insert into ta
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 10 union all
select 110 union all
select 101

create table tb (编号 varchar(10),公交路线 varchar(100))
insert into tb
select '10001', '1,101' union all
select '10002', '10,110'

use PracticeDB
go
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
alter function fn_serch
(
@route varchar(100)
)returns
@temp table(编号 varchar(100),公交路线 varchar(100))
as
begin
;with t
as
(
select a.编号, SUBSTRING(a.公交路线,number,CHARINDEX(',',a.公交路线+',',number)-b.number) col
from tb a join master..spt_values b on b.type='p'
and CHARINDEX(',',','+a.公交路线,number)=number
and number between 1 and len(a.公交路线)
)
insert into @temp
select tb.*
from tb join t on t.编号=tb.编号
where t.col=@route
return
end
go

select * from fn_serch('10')

编号 公交路线
10002 10,110
dawugui 2010-06-01
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 leisang 的回复:]
引用 1 楼 xys_777 的回复:
SQL code
declare @s varchar(10)
set @s='10'

select * from tb where charindex(','+@s+',',','+公交路线+',')>0


测试过了,确实可以用,但是用了charindex后速度慢的不行,十万条的数据,扔到网站上基本查不动啊。。。
[/Quote]
这种查询法确实无法保证速度.
除非更改表结构为:
编号: 公交路线,序号
10001 1 1
10001 101 2
10002 10 1
10002 110 2
dawugui 2010-06-01
  • 打赏
  • 举报
回复
select * from tb where charindex(',10,' , ',' + 公交路线 + ',') > 0

select * from tb where ',' + 公交路线 + ',' like '%,10,%'
leisang 2010-06-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xys_777 的回复:]
SQL code
declare @s varchar(10)
set @s='10'

select * from tb where charindex(','+@s+',',','+公交路线+',')>0
[/Quote]

测试过了,确实可以用,但是用了charindex后速度慢的不行,十万条的数据,扔到网站上基本查不动啊。。。
永生天地 2010-06-01
  • 打赏
  • 举报
回复
declare @s varchar(10)
set @s='10'

select * from tb where charindex(','+@s+',',','+公交路线+',')>0

22,209

社区成员

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

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