sql="select * from A where a like '%,4,%'" sql="select * from A where charindex(',4,',a)>0"4两边加上 ,号是为了区分4、14、40等含有4的数字
解决方案 »
- 如何比较给定一个值如何和查询的一条记录中任意一列相同就返回true?
- select top 10 那个 10 能改成变量吗?
- 求助sql语句
- SQL SERVER2000自动发送邮件,要求带附件的邮件
- 再请问一个过程问题
- 请大家帮忙讨论讨论~~~~~~~~~
- vb 实时错误 -2147219700(80040e14) update 语句错误
- @sql 中的 @datetime 问题
- 聚合含数,分别用MIN,MAX对分组查出的结果是否有区别,更具体的内容,请看,分不多,因我没分了,先谢各位
- mssqlserver并发同事update一条数据
- 急!关于LEFT OUTER JOIN后能否跟一个子查询的问题
- 我想导入一个 word文件,这个表怎莫作阿,怎莫导入阿!!!!!!!!1
union all
select * from A where a =4"
select * from 表 where charindex(',4,',','+a+',')>0--或者:
select * from 表 where patindex('%,4,%',','+a+',')>0
1 4,5
2 3,4
3 4
4 3,4,5
5 2,14,5如果不用','+a+',',你会发现用楼上几位的方法,检索出来的数据是有问题的.
id a
1 1,2
2 2,4,5
3 4
4 3
5 1,4B表中示例数据:
B
id b
1 1,4,7
2 2,5
3 4
所以这样的话就要搜索A表中a字段的规则:如果取B表id=1的A表中的数据:意义:A表中a字段如有有1或4或7都提取。
如果取B表id=3的A表中的数聚:意义:A表中a字段如果有4则提取。如何编写这样的SQL语句呢?
sql="select * from 表 where charindex(',4,',','+a+',')>0 or charindex(',1,',','+a+',')>0"??
select *
from A a
where exists(
select 1
from(
select b from b where id=1
)aa join(
select id=a.id+b.id+1
from(
select id=0 union all select 1
union all select id=2 union all select 3
union all select id=4 union all select 5
union all select id=6 union all select 7
union all select id=8 union all select 9
) a,(
select id=0 union all select 10
union all select id=20 union all select 30
union all select id=40 union all select 50
union all select id=60 union all select 70
union all select id=80 union all select 90
) b
)bb on substring(','+b,id,1)=','
where ','+a.a+',' like '%,'+substring(b,id,charindex(',',b+',',id)-id)+',%'
)
create table A(id int,a varchar(100))
insert a select 1,'1,2'
union all select 2,'2,4,5'
union all select 3,'4'
union all select 4,'3'
union all select 5,'1,4'create table B(id int,b varchar(100))
insert B select 1,'1,4,7'
union all select 2,'2,5'
union all select 3,'4'
go--查询
select *
from A a
where exists(
select 1
from(
select b from b where id=1
)aa join(
select id=a.id+b.id+1
from(
select id=0 union all select 1
union all select id=2 union all select 3
union all select id=4 union all select 5
union all select id=6 union all select 7
union all select id=8 union all select 9
) a,(
select id=0 union all select 10
union all select id=20 union all select 30
union all select id=40 union all select 50
union all select id=60 union all select 70
union all select id=80 union all select 90
) b
)bb on substring(','+b,id,1)=','
where ','+a.a+',' like '%,'+substring(b,id,charindex(',',b+',',id)-id)+',%'
)
go--删除测试
drop table a,b/*--测试结果
id a
----------- ---------------------
1 1,2
2 2,4,5
3 4
5 1,4(所影响的行数为 4 行)
--*/
union all
select * from A where a like '4,%'--'4'前无后有
union all
select * from A where a like '%,4'--'4'后无前有union all
select * from A where a like '%,4,%'--'4'前后都有
(注:会员的感兴趣类别不一定有多少个也可以一个也没有)
请问这样的SQL语句怎么写??谢谢~~~