开发者

Data referencing to both tables in m:n relation

I am working on a mysql based system to manage data from processing of food products. At this point I came across the following specific Problem:

I have a table A with some items:

Farmer      Quantity  
Farmer A    1000 kg  
Farmer B    500 kg

Then I have a table B which is an m:n agregation of data from table A:

Batch       Quantity     Quality etc.  
LI1         200 kg        ....  
LI2         12000 kg      ....

To represent the m:n relation I have a table AB which connects the two:

FK_Farmer    FK_Batch 
FarmerA      LI1   
FarmerB      LI1  
FarmerA      LI2  

Now the problem: some of the batches in Table B are actually made up of other batches... which means they are recursively composed. I am intersted to know what is the best approach in terms of database design to implement this situation.

Should I include an additional foreign key in table AB referencing back to the batches table? Should I not enforce foreign keys and referen开发者_如何学编程ce both the farmers and the batch table through the same column (and add a flag to indicate recursion or something)? Is there any other obvious solution I have ovelooked?

Being able to do drill-down queries for all data through direct MySQL would be nice, but is not necessarily required.


The simplest way to represent the data is to add a Parent pointer to the Batch table. The root of a hierarchy would have a null in this field. Any non-root would point to its parent, which might in turn point to another parent, etc, for as many levels as you may have.

Querying such a structure is tricky because standard SQL has no way to process a tree. Oracle has a proprietary extension in their SQL dialect, but I don't think MySQL does. This means that to chase the whole tree, you have to either write code that loops through queries, or you have to write a query that does multiple joins for some arbitrary number of maximum levels.

But I don't know any easier way around it. Basically I'd plan on chasing the tree with code rather than a single query.


If a parent batch can have multiple child batches, and a child batch can have multiple parent batches, then you need a new mapping table:

FK_ParentBatch  FK_ChildBatch 
LI1             LI5   
LI1             LI6  
LI2             LI5
LI2             LI3
LI3             LI4

Use foreign keys to make sure that the relations are maintained; but I don't know if the database can prevent you from getting into loops, you might have to rely on code or stored procs for that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜