日期:2014-05-18  浏览次数:20611 次

请问sql有没有这样的查询方式?
有2个表,一个用户表,一个服务表,字段大概是这样
a(用户表)
id 姓名
1 张三
2 李思
3 李思杰

b(服务表)
id 服务用户名
1 张三,李思
2 李思杰,李思
3 李思杰,张三

不知道大家有没看明白,就是b表的服务用户名字段里面包含的内容是多个人的名字用,分隔的。
现在我想查李思在b表中有多少条记录应该怎样查啊?
如果服务用户名只有一个人那好查
select count(*) from b where 服务用户名='李思'
但有多人名字在那里,而且可能有些名字某一两个字相同,这样用
select count(*) from b where 服务用户名 like'%李思%' 不行,比如上面的数据这样查出来就是3,显然2才是正确的。请教这种情况下有没有办法查询呢?

------解决方案--------------------
SQL有局限性的
你的数据库设计有问题,多对多应该用三个表
------解决方案--------------------
SQL code
select * from tb where ','+服务用户名+',' like '%,李思,%' 

or

select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0

------解决方案--------------------
SQL code
create table tb(id int,服务用户名 varchar(20))
insert into tb values(1,    '张三,李思') 
insert into tb values(2,    '李思杰,李思') 
insert into tb values(3,    '李思杰,张三')
go
--方法一
select * from tb where ','+服务用户名+',' like '%,李思,%' 
/*
id          服务用户名                
----------- -------------------- 
1           张三,李思
2           李思杰,李思
*/

--方法二
select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0
/*
id          服务用户名                
----------- -------------------- 
1           张三,李思
2           李思杰,李思
*/

drop table tb

------解决方案--------------------
agree潇洒老乌龟
------解决方案--------------------
老乌龟就是潇洒,方法不错。
我还有一个办法,楼主为什么不在服务表里把用户名都用{}括起来呢?
就像这样:
id 服务用户名
1 {张三}{李思}
2 {李思杰}{李思}
3 {李思杰}{张三}

然后:
select count(*) from b where 服务用户名 like '%{李思}%'

PS:
我还是推荐采用“潇洒老乌龟”的做法,因为这符合习惯,呵呵。
------解决方案--------------------
因为李思杰也包含了李思,不满足要求,所以两边都加上一个分隔符','
同意老乌龟
------解决方案--------------------
agree潇洒老乌龟
------解决方案--------------------
select count(*) as 记录条数 from b where charindex('李思',服务用户名) > 0

------解决方案--------------------

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

create FUNCTION [dbo].[Split] (@str_in VARCHAR(8000),@separator VARCHAR(4) )
RETURNS @PrimaryIDTable TABLE (ID VARCHAR(8000))
AS

BEGIN

DECLARE @Occurrences INT,
@Counter INT,
@tmpStr VARCHAR(8000)

SET @Counter = 0
IF SUBSTRING(@str_in,LEN(@str_in),1) <> @separator 
SET @str_in = @str_in + @separator

SET @Occurrences = (DATALENGTH(REPLACE(@str_in,@separator,@separator+'#')) - DATALENGTH(@str_in))/ DATALENGTH(@separator)
SET @tmpStr = @str_in

WHILE @Counter <= @Occurrences 
BEGIN
SET @Counter = @Counter + 1
INSERT INTO @PrimaryIDTable
VALUES ( SUBSTRING(@tmpStr,1,CHARINDEX(@separator,@tmpStr)-1))

SET @tmpStr = SUBSTRING(@tmpStr,CHARINDEX(@separator,@tmpStr)+1,8000)

IF DATALENGTH(@tmpStr) = 0
BREAK
END
RETURN
END

select count(*) from b where '李思'in(select 服务用户名 from dbo.Split(b.服务用户名 ,','))
------解决方案--------------------
select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0
------解决方案--------------------
select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0
------解决方案--------------------