Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cardinality between tables

Status
Not open for further replies.

dbomrrsm

Programmer
Feb 20, 2004
1,709
GB
Does anyone know a simple way of using sql to check the cardinality between two tables to see if the join used is 1:1, 1:M or M:M.

TIA

[bandito] [blue]DBomrrsm[/blue] [bandito]

[blue]Software code, like laws and sausages, should never be examined in production[/blue][black] - [/black][purple]Edward Tenner[/purple]
 
Yes, Dbomrrsm, there are some sneaky methods to use SQL and relational architecture to determine cardinality between two tables:

M:M -- If you are truly limiting your scope to just two tables, then this is not even possible in a relational world...How could you implement a truly M:M relationship? If you have a single column in a child table that points to its parent ID in the master table, just how many different IDs could that single-column Foreign Key (FK) point to?...Just one, not many. To implement a M:M relationship, you must use a third table that cross references the Primary Keys of the two tables that share the M:M (aka "network") relationship. Determine if a table exists that has two or more FKs to two or more tables, and, by definition, that table is a "cross-reference" table between tables that have a de facto M:M relationship.

1:1 -- This is where the trick comes in...if a 1:1 relationship exists between two tables, then there cannot be any duplicates in the foreign key column. Therefore, if a 1:1 relationship exists, there is either already a Unique constraint (or a Unique index) on the FK column, or you can try to create one: if it fails, then there is a 1:M relationship; if it succeeds then there is a de facto 1:1 relationship. If there was no Unique index on the column previously, and if you want the tables to remain 1:1, then just leave the Unique index in place. Here is the code to produce a unique index:
Code:
CREATE UNIQUE INDEX <some name> ON <table name> (<FK column name);

1:M -- If you have a table with an FK and you have ruled out M:M and you have ruled out 1:1, then guess what?...You have a 1:M relationship.

Let us know if this gives you the tactics to identify cardinality.

[santa]Mufasa
(aka Dave of Sandy, Utah, USA)
[ Providing low-cost remote Database Admin services]
Click here to join Utah Oracle Users Group on Tek-Tips if you use Oracle in Utah USA.
 
Dave

Thanks once again for your help.



[bandito] [blue]DBomrrsm[/blue] [bandito]

[blue]Software code, like laws and sausages, should never be examined in production[/blue][black] - [/black][purple]Edward Tenner[/purple]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top