加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

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

发布时间:2020-12-11 23:48:31 所属栏目:MySql教程 来源:网络整理
导读:我正在尝试学习MySQL,所以我创建了一个小博客系统. 我在MySQL中有3个表: 帖子: id | title ----------------1 | Post Title 1 2 | Post Title 2 类别: id | title | parent--------------------------------10 | category10 | 0 11 | category11 | 012 |

我正在尝试学习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上的大量线程.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读