简体   繁体   中英

How to make a self to self relationship in Mysql?

I am using Heidi and I have this Table:

Table Category:

  • id
  • title
  • parent_id

The field parent_id is a reference of id. This way I can do a unlimited Hierarchy of category and sub-category. How do I create this relationship in mysql Syntax?

If you mean how do you create the foreign key constraint, you just need to do something like this:

CREATE TABLE `EXAMPLE` (
    `ID` int(11) NOT NULL,
    `TITLE` varchar(255) NOT NULL,
    `PARENT_ID` int(11) DEFAULT NULL,
    PRIMARY KEY (`ID`),
    KEY `PARENT_ID` (`PARENT_ID`),
    CONSTRAINT `PARENT` FOREIGN KEY (`PARENT_ID`) REFERENCES `EXAMPLE` (`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