mySQL contact table for person AND company - mysql

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.

Related

Can I use 2 primary key (from same table) as foreign key in other table?

I am trying to develop a website. Is a kind of University website. I did a table named ACCOUNTS for admins,students and lecturer as well. So for admin I created manualy an account and this admin can manage things an website and he can create account for the lecturer and send them the details. For students i created a registrasion page where they can apply for a course, the admin decide how is accepted or not (i have a column in accounts named active and by default all account are created with inactive account). Now the problem is on GRADES table. the information which I need it is Grade-ID, Module-ID, theGrade and account_id for student to know how received the grade, but I would like to add the lecturer how marked as well, the problem is that it has same name (account_ID) because is in same table with the students. how should I do?
You can have two columns of the grades table that reference the primary key of the accounts table.
I think that you want something like:
create table grades(
grade_id int primary key,
grade int,
module_id int,
student_id int,
lecturer_id int,
constraint fk_grades_student
foreign key (student_id)
references accounts(account_id),
constraint fk_grades_lecturer
foreign key (lecturer_id)
references accounts(account_id)
);
Demo on DB Fiddle
Please note, however, that this does not ensure that the referenced account really is a lecturer or student (it just makes sure that it exists in accounts). It would be easier to enforce this referential constraint with a different data structure (for example, if there was separated child tables for each account role).

Primary And Foreign key mapping between view and table

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.

Where should the foreign reside in this scenario

I want the relationship to be like a single profile only have one address associated to it. While a single address can be from many profile. Where would I place the foreign key.
Address address_id, state, town, phone, email
Profile username, profile_pic, date_added, password
well since you want one to many relation for address table you should add a foreign key ( let's say addr_id ) to profile table.
That way one address row can be used in multiple profiles
From http://www.mysqltutorial.org/mysql-foreign-key/:
"The customers table is called parent table or referenced table, and the orders table is known as child table or referencing table.
A foreign key can be a column or a set of columns. The columns in the child table often refer to the primary key columns in the parent table."
Looks like you want the foreign key on the user table.
Hope this helps!

Using foreign keys with multiple primary key combinations

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.

EF 4.1 POCO mapping common table

I have two "entity" tables: Provider and User. Both Provider and User can have multiple addresses (shipping, billing, etc.).
Rather then put address information in each entity table, I want to create a table that is common to both of them: An address table. I looked into creating, for instance, an address table with a primary key (identity column), entity type (provider or user), entity key (primary key of the parent entity table) and address type (shipping, etc.), along with the necessary address information.
One trouble I'm having is with foreign key constraints. If I have a foreign key from the parent entity table related to an address row, I found that I have a foreign key violation when I try to insert data.
I was thinking on removing the FK in the tables and then create on EF 4.1 the manual mapping but I dont know how can I do this:
http://i49.tinypic.com/2dt56dv.png (here is the image of the tables - objectid in address table holds userid or providerid and objecttype is a varchar that can be "USER" or "PROV")
How can I get around this? I'd like to use one table for addresses but I can't add a child for one parent without having a related row on the other parent. Of course, I'd like to keep using the foreign keys for referential integrity.
Thanks
this is a pretty common scenario.
[Provider table]
ProviderID (PK)
AddressID
[User table]
UserID (PK)
AddressID
[Address table]
AddressID (PK)
Street1
Street2....
Go into provider table and add a FK from Provider.addressID to Address.AddressID
Go into Users table and add a FK from User.addressID to Address.AddressID
that should work and no FK's will be violated.