我想了解MySQL的入門文章,所以我創建了一個小博客系統。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類= 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的最好的方式,我只是不知道如何還:)
首先,如果你要逃脫你獲取輸入你做一個查詢之前(以防止SQL注入) 這樣的: $ folder_id = $ _GET [ 「類別」]; 應該是: $ folder_id = mysql_real_escape_string(的stripslashes($ _ GET [ 「類別」])); – Tim 2011-05-20 06:11:52
我也建議你閱讀@Denis提供的文章。你會學到很多:)我自己多次閱讀。 – Rifat 2011-05-20 06:49:50
使用MySQL會話變量:http://explainextended.com/2009/09/29/adjacency-list-vs-nested-sets-mysql/。另請參閱此問題的其他選項:http://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database – orangepips 2011-05-23 19:07:19