我想获取4
与当前帖子相关的帖子,比较它们的标签。
每个帖子的标签数量可以有所不同,但最多 - 5;
标签作为数组存储在列JSON
内,如下所示:
["ABBA","SKY","BERN"]
["ALPHA","SKY","SEA", "ABBA"]
["VENUS","EARTH"]
["ABBA","AMSTEL"]
现在假设当前帖子有以下标签:
["ABBA","SKY","BERN"] // row-id = 0
我想获取相关标签row id
。
在上面的示例中,结果应为:
row-id = 1 // because of `SKY` and `ABBA`;
row-id = 3 // because of `ABBA`;
。 依此类推,直到选择了 4 个相关行,按date desc
排序。
像这样:
select id, img, tags from posts
where id <> $currentId
and tags contains any of $current_tags
limit 4
order by date desc.
有什么帮助吗?
您可以进行如下选择:
SELECT id, img, tags FROM posts
WHERE tags LIKE '%"ABBA"%' OR tags LIKE '"%SKY%"' OR tags LIKE '"%BERN%"'
LIMIT 4
ORDER BY date DESC;
在 PHP 中:
$query = "SELECT id, img, tags FROM posts
WHERE tags LIKE '%".implode("%' OR tags LIKE '%", $yourInputArray)."%'
LIMIT 4
ORDER BY date DESC;";
哪里:
$yourInputArray = array("ABBA","SKY","BERN");
由于您最多将有 5 个标签,并且假设JSON_SEARCH可用,您可以尝试以下方法,尽管它有点长。
如果 0 到 4 个索引中的任何一个不存在,JSON_SEARCH将返回 null。
SELECT id, img, tags
FROM posts
WHERE (JSON_SEARCH(@current_tags, 'one', tags ->> '$[0]') is not null
OR JSON_SEARCH(@current_tags, 'one', tags ->> '$[1]') is not null
OR JSON_SEARCH(@current_tags, 'one', tags ->> '$[2]') is not null
OR JSON_SEARCH(@current_tags, 'one', tags ->> '$[3]') is not null
OR JSON_SEARCH(@current_tags, 'one', tags ->> '$[4]') is not null)
LIMIT 4
ORDER BY DATE desc;