Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mysql中查找与一个特定帖子的标签相关的帖子_Sql_Mysql_Tags_Many To Many - Fatal编程技术网

在mysql中查找与一个特定帖子的标签相关的帖子

在mysql中查找与一个特定帖子的标签相关的帖子,sql,mysql,tags,many-to-many,Sql,Mysql,Tags,Many To Many,我有以下表格:Posts(post_is,title和text)、Tags(tag_id,tag)、post_tag_nn(id,tag_id,post_id)。我想要一个特定的帖子,比如有4个标签,所有的帖子都有这些标签,然后所有的帖子都有三个标签,然后所有的帖子都有两个标签,依此类推。如何为此目的构建SQL查询(在php中,这似乎是一个回溯问题=给定集合的所有子集) 如果你打算删除每一篇文章,哪怕只有一个标签,你最好只对每个标签运行一个查询来删除所有带有该标签的文章,然后自己生成集。类似于:

我有以下表格:Posts(post_is,title和text)、Tags(tag_id,tag)、post_tag_nn(id,tag_id,post_id)。我想要一个特定的帖子,比如有4个标签,所有的帖子都有这些标签,然后所有的帖子都有三个标签,然后所有的帖子都有两个标签,依此类推。如何为此目的构建SQL查询(在php中,这似乎是一个回溯问题=给定集合的所有子集)

如果你打算删除每一篇文章,哪怕只有一个标签,你最好只对每个标签运行一个查询来删除所有带有该标签的文章,然后自己生成集。

类似于:

select t.id, t.tag_id, p.post_id, p.title, p.text
  from post_tag_nn as t, posts p
  where p.id = t.post_id
  order by t.id

然后在你的代码中进行分组。当然,您可以进行两种不同的查询,一种是计算标签的顺序和数量,另一种是为每个标签提取帖子。

进行查询以查找当前帖子的标签,如

SELECT tag_id
FROM Post_tag_nn
WHERE post_id = $post_id;
然后使用这些标签id,这个查询应该返回带有4,3,2,。。。匹配标签:

SELECT post_id, COUNT(post_id) AS tag_count
FROM Post_tag_nn
WHERE tag_id IN ($array_of_tag_ids)
GROUP BY post_id
ORDER BY tag_count DESC;

我正在寻找一种sql方法来实现这一点,这种方法比硬编码更有效。