2017-05-05 164 views
0

我有两个表连接但关系是ManyToOne,但我想将它更改为ManyToMany,因为它更适合它,但创建新的ManyToMany表时。MySQL多对多关系表

CostCenter 
IdCostCenter CostCenterNumber CostCenterName 
1   1    Name 1 
2   2    Name 2 


TravelCostCenterLine 
IdCostCenterLine IdTravelComponent SplitLine Percentage IdCostCenter 
1      1    0  25   1 
2      1    0  25   2 
3      1    1  30   1 
4      1    1  20   2 
5      2    0  100   1 

所以我想将其更改为多对多的一个TravelCostCenterLine有多个CostCenter和相同CostCenter可以被分配到多条线路

所以对于我需要多对多的关系表看起来像这样,但我不知道如何使插入填写信息:

LineCostCenterMapping 
IdLineCostCenterMapping IdCostCenter SplitLine IdTravelComponent 
1       1   0   1 
1       2   0   1 
2       1   1   1 
2       2   1   1 
3       1   0   2 

我开始编写插入查询,它会fil此表l数据,但我不知道如何去完成它

INSERT INTO LineCostCenterMapping (IdCostCenter, SplitLine, IdTravelComponent) 
     SELECT 
     ce.IdCostCenter, 
     tcl.SplitLine, 
     tcl.IdTravelComponent 
     FROM TravelCostCenterLine tcl 
     JOIN 
     CostCenter 
     ce ON tcl.IdCostCenter = ce.IdCostCenter; 

因此,它看起来像LineCostCenterMapping例如

+0

在映射表中只是存储IdCostCenter和IdCostCenterLine –

+0

是的,这是另一种方式,但如何编写查询来填充数据? – DanJo

+0

[_Mapping table advice_](http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table) –

回答

0

对于这一点,你必须创建一个新表。 因此,例如表的样子:


CostCenter 

IdCostCenter CostCenterNumber CostCenterName 
1   1    Name 1 
2   2    Name 2 

TravelCostCenterLine 

IdCostCenterLine IdTravelComponent SplitLine Percentage 
1      1    0  25   
2      1    0  25   
3      1    1  30   
4      1    1  20   
5      2    0  100 

那么您应该创建新表与这两个表的关系IDS

third_table 

id  costCenterid    TravelCostCenterLine 
1 primary_key_of_first_table  primary_key_of_second_table 

最后一个表将举行两次基表之间的关系。

1

没有特殊的语法来一补多到许多表,这是通常的INSERT语句,但是你会在LineCostCenterMapping插入值应该已经存在于CostCenterTravelCostCenterLine。确保此约束,你可以在GUI例如ComboBox或与CostCenterTravelCostCenterLine

你能给你的应用程序的更多信息的现有值自动填充字段中使用:编程语言,数据库管理系统...

+0

据我所知,这是简单的插入,但我不知道如何构建它以获得此结果,它是JAVA主要是EJB,EclipseLink JPA和MariaDB – DanJo