我有两个表:tbl_post
和tbl_tags
。
在tbl_post
中,字段tags
包含来自tbl_tags
的ID作为数组。
示例:'1,3,15,20'
或'4,15,6,21'
我想从tbl_post
中选择记录,其字段tags
包含来自tbl_tags
的ID(例如:“ 15”)。
我怎样才能做到这一点?
最佳答案
关于什么:
SELECT * FROM tbl_post WHERE tbl_post.tags LIKE '%15%';
要么
SELECT * FROM tbl_post WHERE Contains(tbl_post.tags, '15');
根据您的评论,您可以尝试
DECLARE @id INT = 15
DECLARE @stringId VARCHAR(50) = CAST(@id AS VARCHAR(50))
SELECT *
FROM tbl_post
WHERE tbl_post.tags = @stringId -- When there is only 1 id in the table
OR tbl_post.tags LIKE @stringId + ',%' -- When the id is the first one
OR tbl_post.tags LIKE '%,' + @stringId + ',%' -- When the id is in the middle
OR tbl_post.tags LIKE '%,' + @stringId -- When the id is at the end
Referenced from this SO post