I have a company table with the following fields:
CompanyID
EmailDomain1
EmailDomain2
EmailDomain3
...
I have another table t with the following fields:
CompanyID
EmailDomain
EmailDomainstat
The following are the constraints:
(CompanyID, emaildomain) should be unique in t;
If an emaildomain of a company gets deleted (email domain could be
any of emaildomain1, emaildomain2 or emaildomain3), the
corresponding companyID and EmailDomain combination should get
automatically deleted.
For example, if a company Abc Inc. has 2 email domains abcinc.in and abc.org, and they plan to remove abcinc.in tomorrow, then I should have the corresponding entry in table t deleted.
How do I get this effect with the help of primary and foreign keys ? I know that the delete on cascade has to be used, but I have no clue on how to bind foreign keys with multiple combinations of primary keys.
Related
I'm planning on creating an "Organizations" table, where the columns are:
Organization Id (primary key), Name, Plan and Company Id (foreign key).
My issue is that per organization there can be multiple companies, that means, I would need to have multiple records with the same Organization Id but with a different Company Id, but since the Organization Id is my primary key I know I can't do this (because it's unique).
How can I structure/design this? It's essentially a one to many relationship between an organization and a company. I'm just starting out with MySQL so I may be missing something obvious.
Drop companyId from the organisations table and have organisationId as foreign key in the companies table.
CREATE TABLE Organizations (
OrganizationId INTEGER,
... other fields,
PRIMARY KEY (OrganizationId)
)
CREATE TABLE Companies (
CompanyId INTEGER,
OrganisationId INTEGER,
... other fields,
PRIMARY KEY (CompanyId),
FOREIGN KEY (OrganisationId) REFERENCES Organizations(OrganisationId)
)
I have 2 tables: person and company.
I want to create a table address knowing that:
a person can have zero, one or several address
a company can have zero, one or several address
the basic rows for address are the same for person and company
Solution 1
Create a table address (no foreign key) with all address rows (street, city...)
Create a person_address with foreign keys address_id and person_id
Create a company_address with foreign keys address_id and company_id
=> A person and company can share the same address (good) and no duplication (good)
=> A bit cumbersome: I frist have to create adress then person/company_address
Solution 2
Create a table person_adress with foreign key person_id and all address rows
Create a table company_adress with foreign key company_id and all address rows again
=> Rows for address info are defined twice
Solution 3?
Is there a way to create an unique table adress which could refer to either a person OR a company?
Thanks to Jacob Barnes for the link:
Foreign Key to multiple tables
Create a "parent table" entity which can either be a person or a company. adress then refers to entity.
I have created 2 table in 2 different databases. First database name is user which contains userDetails table, which have id as a primary key and user_name, and my second database is customer which have 1 table called as customerDetails, which have 1 id as a primary key and customer name and one view of above user table which contains id of that user table and name.
So what i want to do is, creating a foreign key of that view in customerDetails table, so that i can access user table from customer database through view. I don't know how to achieve this, as i am new to database concepts please anyone can get me out of this.
Whole scenario is as follow,
> Database Name : user
> Table Name : userDetails
> Fields : id userName
>
> Database Name : customer
> View Name : user_view
> Fields : id userName
>
> Database Name : customer
> View Name : customerDetails
> Fields : id custName
i want in last table that is in customerDetails last column as a foreign key from view. How can i achieve this?
Views are not related to foreign keys as much as getting to your data as mentioned in comments by your peers. The below uses a Junction Table to intersect users and companies, enforcing a Foreign Key constraint between databases (not a bad idea for shared info between databases).
The Junction Table is many-to-many, and hooks users and companies together.
Schema:
create schema userDB;
create table userDB.userDetails
( id int auto_increment primary key,
userName varchar(100) not null
);
create schema customerDB;
create table customerDB.customerDetails
( id int auto_increment primary key,
custName varchar(100) not null
);
create table customerDB.userCustomerJunction
( -- a many-to-many mapping
id int auto_increment primary key,
userId int not null,
custId int not null,
unique key (userId,custId), -- no dupes allowed
foreign key `ucj_2_user` (userId) references userDB.userDetails(id),
foreign key `ucj_2_cust` (custId) references customerDb.customerDetails(id)
);
Test it:
insert customerDB.customerDetails(custName) values ('Exxon Mobil'); -- id 1
insert customerDB.userCustomerJunction(userId,custId) values (1,7); -- FK Failure
-- above line generates an error 1452 as expected
insert userDB.userDetails(userName) values ('Kelly'); -- id 1
insert customerDB.userCustomerJunction(userId,custId) values (1,1); -- success, FK's satisfied
Remember that the user and company are separate entities and to interface the two would require something that ties them together. A Junction table is a fantastic place to put a column such as effectiveRights or something. It would denote what the user can do, such as insert, update, delete, view, blacklist, etc.
Creating a view between user and company is simply like any join, but in this case it would be between databases with the whichDB. in front of the table name. The view is materialized and manifested in the physical tables. So as the physical rules, the physical has the FK's in force (data integrity). And the addition of an effectiveRights column will assist you in determining what each user and company can do together: such as, yes, this user has certain rights to this company info, etc. With a rights bitmark, or separate columns for rights, all in the Junction table. For an example of Junction tables, see this Answer of mine.
I have created 3 tables in a music tracks database
Track ( id, album, genre)
Album( id, title)
Contributed ( artist, track, role)
I have chosen Id as primary keys for the first table, ( I'd, album) for the second table.
Do I need a primary key in my third table? What is my foreign key? How do I specify my foreign key?What are the unique identifiers in my third table?
I tried to populate it using tracks as foreign key( referenced to Track table, id column) but it gives me error.
Can anyone help?
For the third table, we can have two foreign keys:
Referencing to artist table (assuming we have an artist table with id and name).
Referencing to track table.
Syntax for foreign key should look like this (in create table script):
CONSTRAINT fk_contributed_track FOREIGN KEY
REFERENCS track(id)
Here is an example of a create table script with foreign key.
As far as primary key is concerned, it depends on business rules (i.e. whether one artist can have multiple roles for a track). However, for simple design, I would recommend having a numeric auto increment primary key.
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
MySQL Relationships
I am trying to create a one to many relationship in MySQL with foreign keys.
Two tables, user and location. Each user can have many locations, but each location can have only one user.
How do I configure this? I am using HeidiSQL if that helps, though I can input code as well.
MySQL does not know, nor does it need to know if a relationship is 1-1, or 1-many.
No SQL supports many-many relationships, all require a intermediate table which splits a many-many relationship into 2 separate 1-many.
The difference is in the logic that controls the relationships, which is in the code that you write.
A 1-1 relationship is maintained by having the tables share the same primary key (PK).
With the secondary table declaring that PK as a foreign key pointing to the other tables PK.
Table chinese_mother (
id integer primary key,
name....
Table chinese_child (
id integer primary key,
name ....
....,
foreign key (id) references chinese_mother.id
The direction of the relationship 1 -> many vs many <- 1 is determined by the location of the link field.
Usually every table has a unique id and the link field is called tablename_id.
The table that has the link field in it is the many side of the relationship, the other table is on the 1 side.
Each user can have many locations, but each location can have only one user.
Table user
id: primary key
name......
.....
Table location
id: primary key
user_id foreign key references (user.id)
x
y
.......
By placing the link field in the location table, you force things so that a location can only have 1 user. However a user can have many locations.
There is an example here that is almost exactly what you need foreign keys in innodb
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;
In your example user is the same as parent (a user has many locations, a parent has many childs) and location is the same as child (a location has one user, a child has one parent)