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

前端之家收集整理的这篇文章主要介绍了php – MySQL:从类别中获取帖子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

我在MysqL中有3个表:

帖子:

  1. id | title
  2. ----------------
  3. 1 | Post Title 1
  4. 2 | Post Title 2

类别:

  1. id | title | parent
  2. --------------------------------
  3. 10 | category10 | 0
  4. 11 | category11 | 0
  5. 12 | category12 | 10

post_category_relations:

  1. id | post_id | category_id
  2. ----------------------------------
  3. 1 | 1 | 10
  4. 2 | 2 | 12
  5. 3 | 3 | 11

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

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

PHP中我未完成的片段

  1. $folder_id = $_GET["category"]; // Get Category ID from the URL
  2. $sql = "SELECT * FROM posts
  3. JOIN categories
  4. JOIN post_category_relations
  5. // And I don't really know what should I do here
  6. // because I need the child categories first,then the relations
  7. // then I can get the post too from the post_id of the relations
  8. ";
  9. 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相关文章