I am stuck in a problem where i have to find cardinality of a relationship between tables using mysql. Following this post
MySQL: How to determine foreign key relationships programmatically?
I have found all tables related to my table and the columns which are foreign key. Now i also want to find the cardinality of relationship i.e. one-to-one, one-to-many or many-to-many. Any ideas or snippets would be highly appreciated
相关问题
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- MySQL: conduct a basic search
- Why sometimes there is one of more gap(s) in the v
- mySQL alter table on update, current timestamp
Let us assume that table
A
has a foreign keyf
which refers to the primary keyk
of tableB
. Then you can learn the following from the schema:UNIQUE
constraint onA.f
, then there can be at most one row inA
for every row inB
. Note that in the case of multi-column indices, all columns of the unique constraint must be part of the foreign key. You can useSHOW INDEX FROM tablename WHERE Non_unique = 0
to obtain information on the uniqueness constraints of a table.A.f
is declaredNOT NULL
, then there will always be at least one row inB
for every row inA
. You can useSHOW COLUMNS FROM tablename
to list the columns and see which of them allowNULL
values.If you interpret “one” as “zero or one”, then you get a one-to-one relation using a unique constraint, and a many-to-one relation (i.e. many rows in
A
referring to one row inB
) without such a unique constraint.A many-to-many relation would be modeled using a separate table, where each row represents one element of the relation, with many-to-one relations for both foreign keys it contains.