我有两个表:tbl_posttbl_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

10-06 14:06
查看更多