简体   繁体   中英

Best way to organize this structure?

I have a database of foods, which I would like to divide into a tree structure of categories, subcategories and sub-subcategories. For example,

fruits -> apples -> fuji, or fruits -> apples -> cortland

I would like each parent page to show its immediate children (fruits page shows apples, oranges and all other fruit; apples page shows fuji, cortland and all other apples).

Also, I would like each node to know all its parent nodes. (fuji knows that its parent is apple, whose parent is fruit)

What is the best way to store this tree-like relationship using MySQL?

我建议阅读《 在MySQL中管理分层数据》

You could try something like:

Table category:

id INT AUTO INCREMENT PRIMARY KEY
parent_id INT
name VARCHAR(40)

Then when you want to display all the sub-categories of fruit you can do:

SELECT C.* FROM category C WHERE C.parent_id = {$currentCategory}
CREATE TABLE Food (
    Id INT NOT NULL AUTO_INCREMENT,
    Name CHAR(50) NOT NULL,
    CategoryId INT,
    PRIMARY_KEY(Id),
    FOREIGN KEY (CategoryId) REFERENCES FoodCategory (Id))
CREATE TABLE FoodCategory (
    Id INT NOT NULL AUTO_INCREMENT,
    Name CHAR(50) NOT NULL,
    ParentCategoryId INT,
    PRIMARY_KEY(Id),
    FOREIGN KEY (ParentCategoryId) REFERENCES FoodCategory (Id))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM