php – MySQL:从类别中获取帖子

我正在尝试学习MySQL,所以我创建了一个博客系统.

我在MysqL中有3个表:

帖子:

id    |  title      
----------------
1     |  Post Title 1         
2     |  Post Title 2  

类别:

id    |  title          | parent
--------------------------------
10     |  category10    | 0 
11     |  category11    | 0
12     |  category12    | 10 

post_category_relations:

id    |  post_id   |   category_id
----------------------------------
1     |  1         |   10
2     |  2         |   12
3     |  3         |   11

每个帖子可以有多个类别,它们的关系存储在post_category_relations中:

因此,当我访问index.PHP?category = 10时,我想让每个帖子与category10相关,包括其子文件夹category12中的帖子.

PHP中我未完成的片段

$folder_id = $_GET["category"]; // Get Category ID from the URL
$sql = "SELECT * FROM posts 
          JOIN categories
          JOIN post_category_relations
        // And I don't really kNow what should I do here
        // because I need the child categories first,then the relations
        // then I can get the post too from the post_id of the relations
       ";
MysqL_query($sql);

我知道这将需要高级MysqL技能,但任何帮助表示赞赏!我已经用PHP制作了这个,但我需要使用4个循环,这不是最好的方法,当它在MysqL中可能时,我只是不知道如何:)

最佳答案
您可能会发现Phillip Keller的这些文章很有趣:

> Tags: Database schemas
> Tagsystems: performance tests

它们涵盖了标签,但您的查询(即category1和category2与category1或category2以及您尝试编写的那些)几乎相同.

另见关于索引分层数据的讨论:Managing Hierarchical Data in MySQL.

以及与嵌套集,标签,类别等相关的SO上的大量线程.

相关文章

优化MySQL数据库发布系统存储的方法有:1.mysql库主从读写分...
使用mysql的方法:在“我的电脑”→右键→“管理”→“服务”...
在mysql中查看root用户权限的方法:1.命令行启动mysql服务;...
MySQL主从复制是用来备份一个与主数据库一样环境的从数据库,...
运行mysql的方法1.启动mysql服务,在“我的电脑”→右键→“...
开启mysql的方法1.可以通过快捷键win+r,输入cmd,打开窗口,...