微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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上的大量线程.

原文地址:https://www.jb51.cc/mysql/433010.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐