【发布时间】:2011-08-29 09:53:21
【问题描述】:
我正在努力学习 MySQL,所以我创建了一个小博客系统。
我在 MySQL 中有 3 个表:
posts:
id | title
----------------
1 | Post Title 1
2 | Post Title 2
categories:
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 中可能不是最好的方法,我只是还不知道如何:)
【问题讨论】:
-
首先,如果您应该在执行查询之前转义您的 get 输入(以防止 SQL 注入):$folder_id = $_GET["category"];应该是:$folder_id = mysql_real_escape_string(stripslashes($_GET["category"]));
-
我还建议您阅读@Denis 提供的文章。你会学到很多东西:)我自己读了好几遍。
-
使用 MySQL 会话变量:explainextended.com/2009/09/29/…。另请参阅此问题以获取其他选项:stackoverflow.com/questions/4048151/…
标签: php mysql hierarchical-data database-relations