我試圖圍繞查詢具有層次結構類別數據(用於cms)的表進行打包,該表還與我的帖子數據和多對多類型關係綁定我的post2cat表。具體來說,我的問題是,如何獲取屬於某個特定類別ID的任何子類別的所有帖子(不限於直接後裔,但可以是n級)?這裏是我的表:需要分層Mysql查詢的幫助
'類' 表:
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(45) | YES | | NULL | |
| parent_id | int(11) | YES | MUL | 0 | |
+-----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
'post2cat' 表:
+---------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| post_id | int(11) | NO | MUL | NULL | |
| cat_id | int(11) | NO | MUL | NULL | |
+---------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
'帖子' 表:
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(256) | NO | | NULL | |
| content | text | NO | | NULL | |
| end_date | datetime | NO | | NULL | |
| format_id | int(11) | NO | | NULL | |
| featured | int(1) | NO | | NULL | |
| status | int(3) | NO | | NULL | |
| publish_date | datetime | NO | | NULL | |
| date_created | datetime | NO | | NULL | |
| date_modified | datetime | NO | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
POST_ID名稱描述
post2cat
你'類別'表是一個鄰接表模型。使用MySQL會話變量來遍歷樹。我關於SQL中的分層數據的問題涵蓋了更多關於這個一般問題的內容:http://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-數據庫 – orangepips 2011-04-19 14:38:08