简体   繁体   中英

how to get related post comparing their json tags

I want to get 4 related posts with a current one, comparing their tags.

Number of tags per post can vary but max - 5;

Tags are stored inside JSON column as an array, like this:

["ABBA","SKY","BERN"]  
["ALPHA","SKY","SEA", "ABBA"]  
["VENUS","EARTH"]
["ABBA","AMSTEL"]

Now suppose the current post has this tags:

["ABBA","SKY","BERN"] // row-id = 0

I want to get row id of related tags.

In the above example result should be:

row-id = 1 // because of `SKY` and `ABBA`;  
row-id = 3 // because of `ABBA`;

... ans so on untill 4 related rows are selected, ordered by date desc .

Something like this:

select id, img, tags from posts
where id <> $currentId
and tags contains any of $current_tags
limit 4
order by date desc.

Any help?

You can make a selection like this:

SELECT id, img, tags FROM posts
WHERE tags LIKE '%"ABBA"%' OR tags LIKE '"%SKY%"' OR tags LIKE '"%BERN%"'
LIMIT 4
ORDER BY date DESC;

In PHP:

$query = "SELECT id, img, tags FROM posts
WHERE tags LIKE '%".implode("%' OR tags LIKE '%", $yourInputArray)."%'
LIMIT 4
ORDER BY date DESC;";

Where:

$yourInputArray = array("ABBA","SKY","BERN");

Since you will be having a max of 5 tags, and assuming JSON_SEARCH is available, you could try the following, though it is a bit long.

JSON_SEARCH will return null if any of the 0 to 4 indices do not exist.

    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;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM