我有两个表权限和多对多关系组
CREATE TABLE `permissions` (
`Permission_Id` int(11) NOT NULL AUTO_INCREMENT,
`Permission_Name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Permission_Id`)
)
群组表
CREATE TABLE `groups` (
`Group_Id` int(11) NOT NULL AUTO_INCREMENT,
`Group_Desc` varchar(100) DEFAULT NULL,
PRIMARY KEY (`Group_Id`)
)
我很困惑如何实现多对多的关系
最好在新表中创建Group_id和Permission_id的复合主键
或者创建一个新表&使用join关键字从两个表中选择列。
答案 0 :(得分:1)
来自my blog:
这样做。
CREATE TABLE XtoY (
# No surrogate id for this table
x_id MEDIUMINT UNSIGNED NOT NULL, -- For JOINing to one table
y_id MEDIUMINT UNSIGNED NOT NULL, -- For JOINing to the other table
# Include other fields specific to the 'relation'
PRIMARY KEY(x_id, y_id), -- When starting with X
INDEX (y_id, x_id) -- When starting with Y
) ENGINE=InnoDB;
注意:
⚈ Lack of an AUTO_INCREMENT id for this table -- The PK given is the 'natural' PK; there is no good reason for a surrogate.
⚈ "MEDIUMINT" -- This is a reminder that all INTs should be made as small as is safe (smaller ⇒ faster). Of course the declaration here must match the definition in the table being linked to.
⚈ "UNSIGNED" -- Nearly all INTs may as well be declared non-negative
⚈ "NOT NULL" -- Well, that's true, isn't it?
⚈ "InnoDB" -- More effecient than MyISAM because of the way the PRIMARY KEY is clustered with the data in InnoDB.
⚈ "INDEX(y_id, x_id)" -- The PRIMARY KEY makes it efficient to go one direction; this index makes the other direction efficient. No need to say UNIQUE; that would be extra effort on INSERTs.
⚈ In the secondary index, saying just INDEX(y_id) would work because it would implicit include x_id. But I would rather make it more obvious that I am hoping for a 'covering' index.
要有条件地插入新链接,请使用IODKU
请注意,如果此表中有AUTO_INCREMENT,IODKU会“烧掉”#34; ids很快。
更多强>
FOREIGN KEY
隐含地在所涉及的列上创建索引。
PRIMARY KEY(a,b)
(1)表示组合(a,b)
为UNIQUE
,(2)按(a,b)
对数据进行排序。
INDEX(a), INDEX(b)
(由FOREIGN KEY
生成或手动生成) 与INDEX(a,b)
相同。
InnoDB真的需要一个PRIMARY KEY
,所以你也可以说PRIMARY KEY (a,b)
而不是 UNIQUE(a,b)
。
答案 1 :(得分:0)
我知道解决方案。
我需要创建"交汇点"在这种情况下,表可以保持多对多关系。
CREATE TABLE Groups_Permissions
(
Group_Id INT,
Permission_Id INT,
)
Group_Id和Permmission_Id的组合应该是UNIQUE并且具有FK到组和权限表。