MySQL是一款主流的關系型數據庫管理系統,可用于創建多對多關系圖。為了創建多對多關系圖,我們需要進行以下幾個步驟:
1. 創建表
CREATE TABLE `table1` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `table2` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `relationship` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `table1_id` INT(11) NOT NULL, `table2_id` INT(11) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`table1_id`) REFERENCES `table1` (`id`), FOREIGN KEY (`table2_id`) REFERENCES `table2` (`id`) );
2. 插入數據
INSERT INTO `table1` (`name`) VALUES ('A'); INSERT INTO `table2` (`name`) VALUES ('X'); INSERT INTO `table2` (`name`) VALUES ('Y'); INSERT INTO `relationship` (`table1_id`, `table2_id`) VALUES (1, 1); INSERT INTO `relationship` (`table1_id`, `table2_id`) VALUES (1, 2);
3. 查詢數據
SELECT table1.name AS table1_name, table2.name AS table2_name FROM relationship JOIN table1 ON table1.id = relationship.table1_id JOIN table2 ON table2.id = relationship.table2_id;
以上就是通過MySQL創建多對多關系圖的過程。通過這種方式,我們可以方便地建立表之間的多對多關系。
上一篇mysql 創建唯一鍵
下一篇mysql 創建復合索引