I have a Post table in SQL Server and for performance reason, this table has a column(UsersWhoLiked) in the form of comma separated values that specify which UserIds that liked a Post as following.
Id | Subject | UsersWhoLiked
---|---------|-----------
1 | red | u1,u2
2 | blue | u2, u3,u4,u5
3 | green |
4 | gray | u3, u4, u7
I want to write a query that gets UserId as a parameter and return List of Post as a result so that in the result, every post have a column that specifies the user liked or not the post.
Example: For UserId: u3
I expect that:
Id | Subject | Liked
---|---------|-----------
1 | red | 0
2 | blue | 1
3 | green | 0
4 | gray | 1
Query:
SELECT Id, Subject FROM Post
But I don't know how to add Liked column to the Select statement
You can use the following:
SELECT Id, Subject,
IIF(CHARINDEX('u3,', REPLACE(CONCAT(UsersWhoLiked, ','), ' ', '')) > 0, 1, 0) AS Liked
FROM Post
You should use a second table to store the likes:
CREATE TABLE PostLikes (
PostId INT FOREIGN KEY REFERENCES Post(Id),
UserId INT FOREIGN KEY REFERENCES Users(Id),
CONSTRAINT PK_PostLikes PRIMARY KEY (PostId, UserId)
);
So you can use the following SELECT
to get the expected information:
SELECT Id, Subject, IIF(ISNULL(PostLikes.UserId, 0) > 0, 1, 0) AS Liked
FROM Post LEFT JOIN PostLikes ON Post.Id = PostLikes.PostId AND PostLikes.UserId = 3
You can try the below:
DECLARE @id varchar(10)='u3'
SELECT Id, Subject,
CASE WHEN (',' + UsersWhoLiked + ',') LIKE '%,'+@id+',%' THEN 1 ELSE 0 END Liked
FROM Post
I don't how storing comma separated values improves performance, but this is bad idea. In your case you should be careful with substrings. Such as, if you are looking for u3
, it should not match u31
. So put ,
before and after each value in UsersWhoLiked
column
declare @userId varchar(10) = 'u3'
select
Id, Subject
, Liked = isnull(sign(charindex(',' + @userId + ',', ',' + UsersWhoLiked + ',')), 0)
from Post
select *, case PATINDEX('%u3%', userwholikes) --dont use u3(comma), only use u3
when 0 then --because u3 becomes last one
0
else 1
end likes
from yourtable
i give this, by my understanding..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.