mysql 多标签搜索

lo8azlld  于 2023-08-02  发布在  Mysql
关注(0)|答案(4)|浏览(164)

我正在尝试在我的文章标签中进行多标签搜索。所以我有一个表tags_posts(列是id_tagid_post)。
如果用户输入几个标签(我将使用逗号和数组分离和解析它们),SQL查询应该返回所有帖子,在用户的输入中有所有标签。
我尝试过的:

SELECT DISTINCT id_post, content, author_id, created, updated, username 
FROM tags_posts 
INNER JOIN posts ON posts.id=tags_posts.id_post 
INNER JOIN users ON users.id=posts.author_id 
WHERE id_tag IN (1,2,3)

字符串
但在这种情况下,如果任何一个标签id在任何帖子中有,该帖子将返回。但我在找那篇文章的所有标签。

aij0ehis

aij0ehis1#

试试看

SELECT * 
  FROM posts a JOIN
(
 SELECT p.id
   FROM tag_posts tp JOIN posts p 
     ON tp.post_id = p.id JOIN tags t 
     ON tp.tag_id = t.id
  WHERE t.name IN ('tag1', 'tag2', 'tag3')
  GROUP BY p.id
 HAVING COUNT(DISTINCT t.id) = 3 -- << should the number of tags used in WHERE clause
) q ON a.id = q.id

字符串
HAVING子句确保查询仅返回具有all(示例中为三个)标签的帖子。
下面是SQLFiddledemo

osh3o9ms

osh3o9ms2#

SELECT posts.id, posts.content, posts.created, posts.updated, posts.author_id, users.username 
FROM posts 
INNER JOIN users
    on users.id = posts.author_id 
INNER JOIN tags_posts 
    ON tags_posts.id_post = posts.id
INNER JOIN tags 
    ON tags.id = tags_posts.id_tag 
WHERE tags.name = 'tag1' 
    AND tags.name = 'tag2' 
    AND tags.name = 'tag3'

字符串

b1payxdu

b1payxdu3#

传递要搜索的标签ID,用逗号分隔,例如$search,然后使用以下查询:

select id_post from tags_posts where id_tag  IN ($search)

字符串

9nvpjoqh

9nvpjoqh4#

你可以使用MySQL中的“IN”语句来解析标记吗?

SELECT *
FROM Posts
LEFT JOIN Tag_Posts 
    ON Tag_Posts.Id_post = Posts.id
INNER JOIN Tags
    ON Tags.id = Tag_Posts.Id_tag
WHERE Tags.name IN('PHP','SQL','LAMP')

字符串

相关问题