您可以首先创建一个函数,该函数采用 user.activities 字符串并将字符串拆分为活动 int id,如下所示:
create FUNCTION dbo.SplitStringToIds (@acts nvarchar(MAX))
RETURNS @acivityids TABLE (Id int)
AS
BEGIN
DECLARE @stringToInsert nvarchar (max)
set @stringToInsert=''
DECLARE @intToInsert int
set @intToInsert=0
DECLARE @stidx int
set @stidx=0
DECLARE @endidx int
set @endidx=0
WHILE LEN(@acts) > 3
BEGIN
set @stidx=CHARINDEX('-', @acts, 1)
set @acts=substring(@acts,@stidx+1,len(@acts))
set @endidx=CHARINDEX('-', @acts, 1)-1
set @stringToInsert=substring(@acts,1,@endidx)
set @intToInsert=cast(@stringToInsert as int)
INSERT INTO @acivityids
VALUES
(
@intToInsert
)
END
-- Return the result of the function
RETURN
结束
然后你可以尝试这样的事情来让用户有 2 个或更多相同活动的用户 id=3
select u.id,count(u.id) as ActivitiesCounter from users as u
cross apply SplitStringToIds(u.activities) as v
where v.id in (select v.id from users as u
cross apply SplitStringToIds(u.activities) as v
where u.id=3)
group by u.id having count(u.id)>=2
但我认为这种存储表之间关系的方式只会给你带来麻烦,如果可以的话,最好添加一个关系表。