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
Let us assume that table A has a foreign key f which refers to the primary key k of table B. Then you can learn the following from the schema:
If there is a UNIQUE constraint on A.f, then there can be at most one row in A for every row in B. Note that in the case of multi-column indices, all columns of the unique constraint must be part of the foreign key. You can use SHOW INDEX FROM tablename WHERE Non_unique = 0 to obtain information on the uniqueness constraints of a table.
If A.f is declared NOT NULL, then there will always be at least one row in B for every row in A. You can use SHOW COLUMNS FROM tablename to list the columns and see which of them allow NULL 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 in B) 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.
Related
I have seen similar posts and have not found a definitive answer.
I have a series of tables that store data about certain events. Each of these tables have the same structure. Each of these tables has a foreign key constraint for an id showing what item the data is related to.
Each of these tables id structure is also the same CHAR(24). The tables these ids come from must remain separate because they are all completely different.
I am interested in combining all of my data tables into one with a foreign key being constrained to one of 3 tables. So, a row in my data table will have to have an id that is present in one of the three tables. Additionally this foreign key will need the possibility of ON DELETE settings. Is this possible? And to that, is this poor design?
Items A
- id
- ...
Items B
- id
- ...
Items C
- id
- ...
Data
- id FK
No. What you're describing is sometimes called polymorphic-associations but it should be a clue that it's not good design because you can't make a foreign key constraint for it. That is, the FOREIGN KEY syntax only allows you to reference one table, not three.
The only way you could make a real foreign key constraint that performs ON DELETE actions is to make three separate foreign keys:
Data
- idA FK
- idB FK
- idC FK
For a given row in Data, presumably only one of these three foreign keys would be non-NULL. The other two would be NULL. Ensuring this could be done in a trigger or CHECK constraint, or else you would just have to implement it in application logic (i.e. don't insert a row with more than one of these columns non-NULL).
Polymorphic associations, that is storing a single column that may reference one of three different tables, is not a valid relational design.
You can see past answers I've written about polymorphic associations: https://stackoverflow.com/search?q=%5Bpolymorphic-associations%5D+user%3A20860
I have:
Table Review with column item_id (not pk)
Table Product with column id (pk)
Table Business with column id (pk)
Relationships:
Review.item_id references Product.id
Review.item_id references Business.id
These relationships are 1:M
What is the syntax in MySQL for one column field to reference IDs from two different tables?
My research lead me to believe you cannot have one foreign key reference two different tables.
My conclusions so far (based on links provided below):
Use a foreign key without a foreign key constraint
Use field to reference other records, but do not create a foreign key constraint
Polymorphic Associations. The foreign key may reference rows in any of several related tables.
One foreign key can reference only one table
These conclusions seem logical to me, but I can't figure out the syntax.
links:
MYSQL - One Column Referenced to Multiple Table
Is it possible to reference one column as multiple foreign keys?
MySQL - Conditional Foreign Key Constraints
I'm using MySQL 5.7 with WB6.3 for my study project to design the ER diagram.
When I try to create many-to-many relationship. By default MySQL will mark the primary keys of both tables as primary key in the lookup table as well.
Is it really need to have primary keys from both table as primary key in the lookup table as well ?
Please see the table car_item in my diagram below I've removed primary key from both red(idcar,iditem). Please tell me if PK is needed for them
There should be a unique key for (car_idcar, item_list_iditem_list), but it doesn't necessarily have to be the primary key. This way, you ensure that you don't create duplicate relationships between the same rows in the two tables.
A table can only have one primary key, and the car_item table already has primary key id_car_item, so the foreign keys for the relation can't also be a primary key. But there can be an arbitrary number of unique keys.
Some purists might say that if there are two unique keys (a primary key is also a unique key), one of them is redundant. In your case, the id_car_item column may not really be necessary, as it's not common to refer to relations in other tables, the relation table is just used to join the other two tables. But this isn't always the case. For instance, a user table might have a unique username column (since you don't allow multiple users to have the same name), but also a userid primary key that's used as the foreign key in other tables (this allows renaming users without having to update all the foreign keys). Some database designers like to have an auto-increment column in every table, as it's useful as a reference in user interface applications.
It is common practice to have a composite primary key in a table that implements many-to-many. This key should consist of primary keys from both tables on each side of the many-to-many relationship.
Such approach guarantees data consistency and eliminates duplication.
In your case you should define a composite primary key for table car_item that would consist of two fields { car_idcar, item_list_iditem_list }
The column id_car_item is not needed and can be dropped, it was probably added automatically, as many RDBMS add surrogate PK by default.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
mySQL's KEY keyword?
Like
PRIMARY KEY (ID),
KEY name (name),
KEY desc (desc),
etc.
what are they useful for?
Keys are used to enforce referential integrity in your database.
A primary key is, as its name suggests, the primary identification of a given row in your table. That is, each row's primary key will uniquely identify that row.
A unique key is a key that enforces uniqueness on that set of columns. It is similar to a primary key in that it will also uniquely identify a row in a table. However, there is the added benefit of allowing NULL in some of those combinations. There can only be 1 primary key, but you can have many unique keys.
A foreign key is used to enforce a relationship between 2 tables (think parent/child table). That way, a child table can not have a value of X in its parent column unless X actually appears in the parent table. This prevents orphaned records from appearing.
The primary key constraint ensures that the column(s) are:
not null
unique (unique sets if more than one column)
KEY is MySQL's terminology in CREATE TABLE statements for an index. Indexes are not ANSI currently, but all databases use indexes to speed up data retrieval (at the cost of insertion/update/deletion, because of maintenance to keep the index relevant).
There are other key constraints:
unique
foreign key (for referential integrity)
...but your question doesn't include examples of them.
keys are also called indexes. They are used for speeding up queries. Additionally keys can be constrains (unique key and foreign key). The primary key is also unique key and it identifies the records. The record can have other unique keys as well, that do not allow to duplicate a value in a given column. Foreign key enforces referential integrity (#Derek Kromm already wrote excellent description). The ordinary key is used only for speeding up queries. You need to index the columns used in the WHERE clause of the queries. If you have no index on the column, MySQL will need to read the whole table to find the records you need. When index is used, MySQL reads only the index (which is usually a B+ tree) and then read only those record from the table it found in the index.
Primary KEY is for creating unique/not null constraint for each row in the table. Also searching by this key is the fastest. You can create only one PK in the table.
Ordinary key/index is key for speeding your searching by this column, sorting, grouping and joining with other table by this key.
Indexes drawback:
Adding new indexes to table will influence on speed or running insert/update/delete statements. So you should select columns for indexing in your table very carefully.
Key are used for relation purposes between tables and you are able to create joins in order to select data from multiple tables
What, you didn't fine the wikipedia entry comprehensive? ;-)
So, a key, in a relational database (such as MySQL, PostgreSQL, Oracle, etc) is a data constraint on a column or set of columns. The most common keys are the Primary key and foreign keys and unique keys.
A foreign key specifically relates the data of one table to data in another table. You might see that a table blog_posts has a foreign key to users based on a user_id column. This means that every user_id in blog_posts will have a corresponding entry in the users column (this is a one-to-many relationship -- a topic for another time).
If a column (or group of columns) has a unique key, that means that there can only be one such incidence of the key in the table. Often you'll see things like email addresses be unique keys -- you only want one email address per user. I've also seen a combination of columns match to a unique key -- the five columns, first_name, last_name, address, city, and state, will often be a unique key -- realistically, there can only be one William Gates at 1835 73rd Ave NE, Medina, Washington. (I do realize that it is possible for a William Gates Jr. to be born, but the designers of that database didn't really care).
The primary key is the primary, unique identifier of a given table. By definition it is a unique key. It is something which cannot be null and must be unique. It holds a special place of prominence among the indexes of a given table.
I have two tables, let's say they are called table A and table B. An item from table B can be present in multiple instances of A, and each A can contain multiple Bs so I have a table called a_b which links them together by their primary keys. My question is when I define this association table, should I have a primary key on the association table? Or is it not needed? Just trying to avoid ending up on TDWTF, that's all :)
The primary key would be on the table A PK column and table B PK column in your association table. That way, you ensure you don't get any duplicate rows in your association table by accident.
One of the main purposes of primary keys is to guarantee referential integrity. That is, keep the data in your table clean, with no duplicates. The PK in this case will ensure you never have 2 duplicate rows in the association table.
I think you might want to use a primary key in order to show your intent. If for example you do not want
a, b
a, b
Then a primary key defined on A.a and B.b would make that more clear. If you don't care, but you have a,b and other fields, then adding a surrogate key as your primary key might help in giving you a uniform way to delete a row that you do not want. Otherwise you will have to delete where a=a and b=b and ?? then pick some field value from the row you want deleted. Whereas with a surrogate key you can just pick the row and say delete where mykey = 36 or something...
But really it depends on the business case. Many intersect tables have some kind of date range, or additional fields related to the relationship in addition to the keys of the two tables. Defining a primary key on the existing columns, a new surrogate key, some unique indexes, some constraints, or even having no indexes could all be valid courses of action depending upon your needs.
I would say definitely do whatever makes your intentions the most clear.
Not needed. Both keys should form the primary key of your association table. If you're going to be doing bidirectional navigation, consider adding an index with the keys reversed.
The primary key is needed always.
However, I'd say it depends what should it be. If you are going to use some sort of ORM systems (e.g. Hibernate) then it is best to have a surrogate identifier, while those two foreign keys (pointing to tables A and B) should form a unique index.
Also, if there would ever be a need to reference such a relationship from another table then this surrogate identifier would be really handy.