Ada*_*dam 5 php mysql database-relations hierarchical-data
我正在尝试学习MySQL,所以我创建了一个小博客系统.
我在MySQL中有3个表:
posts :
id | title
----------------
1 | Post Title 1
2 | Post Title 2
Run Code Online (Sandbox Code Playgroud)
categories :
id | title | parent
--------------------------------
10 | category10 | 0
11 | category11 | 0
12 | category12 | 10
Run Code Online (Sandbox Code Playgroud)
post_category_relations :
id | post_id | category_id
----------------------------------
1 | 1 | 10
2 | 2 | 12
3 | 3 | 11
Run Code Online (Sandbox Code Playgroud)
每个帖子可以有多个类别,它们的关系存储在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);
Run Code Online (Sandbox Code Playgroud)
我知道这将需要高级MySQL技能,但任何帮助表示赞赏!我已经用PHP制作了这个,但我需要使用4个循环,这不是最好的方法,当它在MySQL中可能时,我只是不知道如何:)
我无法测试我的查询,但我相信类似
select * from posts,post_category_relations where post.id=post_category_relations.post_id and
post_category_relations.category_id in (select id from categories where id=? or parent=?)
Run Code Online (Sandbox Code Playgroud)
就是您正在寻找的。
| 归档时间: |
|
| 查看次数: |
1322 次 |
| 最近记录: |