Database theory - relationship between two tables

岁酱吖の 提交于 2019-12-12 13:37:23

问题


I have a database with two tables - let's call them Foo and Bar. Each foo may be related to any number of bars, and each bar may be related to any number of foos. I want to be able to retrieve, with one query, the foos that are associated with a certain bar, and the bars that are associated with a certain foo.

My question is, what is the best way of recording these relationships? Should I have a separate table with records of each relationship (e.g. two columns, foo and bar)? Should the foo table have a column for a list of bars, and vice versa? Is there another option that I'm overlooking?


回答1:


That's called a many-to-many relationship. The "standard" solution is to set up a third table, with the primary key from each table in each row where there is a relationship.

The third table is called a junction table. "Junction table" from Wikipedia: http://en.wikipedia.org/wiki/Junction_table

As an example:

Foo
UID
Col1
Col2

Bar
UID
Col1
Col2

Foo_Bar
UID
Foo_UID
Bar_UID

So, in the above, there could be many foos and many bars. Each foo that relates to a bar and each bar that relates to a foo would exist in the Foo_Bar table. To get all the foos that relate to a given bar, you could use the following SQL:

select *
from foo
where uid in (
    select foo_uid
    from foo_bar
    where bar_uid=<some bar uid>)

(Didn't find any exact dupes of this question, but the following questions expand on the topic.)

Many to many table design question
Many to Many Relation Design - Intersection Table Design




回答2:


It is indeed a many to many relation ship. In addition to Michael's answer, I wanted to provide the following as additional resource. I've seen too many poor database implementation to not bring this up (not just for you but other who might view this in the future)

  • http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php


来源:https://stackoverflow.com/questions/2457703/database-theory-relationship-between-two-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!