Primary And Foreign key mapping between view and table - mysql

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.

Related

How to reference one column by multiple tables columns primary keys

I have a database consist of 3 tables each table indicate one user like this:
Admin table 'User 1'.
Staff table 'User 2'.
Student table 'user 3'.
I want to implement a common table between them called 'POST'
WHERE each user can post content to the post table content column,
however I need to Identify the type of posters ' the one who posted the post ' so I'm adding a column
user_type to the table POST
the column user_type should hold the ID of the USER ' Admin, Staff, Student '
I'm in a case where I want to be able to refer to this column ( user_type) in the POST table to multiple table columns Admin table, Staff table, Student table. So
I Can identify the USER who posted the post.
All these kind of users are persons that you need to store in one parent table called "Users" or "Persons" from which the parent's table are "User 1", "User 2", "User 3"...
This is called inheritance in data modeling.
Thus you can join the post table to the father table.
As an example :
CREATE TABLE T_PERSON_PRS (PRS_ID INT IDENTITY PRIMARY KEY, PRS_NAME...)
CREATE TABLE T_PERSON_ADMIN_PAM (PRS_ID INT PRIMARY KEY FOREIGN KEY T_PERSON_PRS (PRS_ID), ... )
CREATE TABLE T_PERSON_STAFF_PSF (PRS_ID INT PRIMARY KEY FOREIGN KEY T_PERSON_PRS (PRS_ID), ... )
CREATE TABLE T_PERSON_STUDENT_PSD (PRS_ID INT PRIMARY KEY FOREIGN KEY T_PERSON_PRS (PRS_ID), ... )
CREATE TABLE T_POST_PST (PST_ID INT IDENTITY PRIMARY KEY, PRS_ID INT PRIMARY KEY FOREIGN KEY T_PERSON_PRS (PRS_ID), ...)

Table inside another table in MySQL

I made a database called users in which it has a name, password and phone number, but I want this user to have another table that stores current_capital, current_percentage and current_date of that user but I do not know how to do it, some advice ?
I have the telephone number in the user database as the primary key.
It is advisable to have a database for each user? or better to these attributes (save capital_actual, current_percent and current_date) I add an attribute identifier_user that would be the phone number and put everything in a second table? (as records table)
Thanks.
When using databases, you want to have a data model with a fixed set of tables and columns. You then add data by adding rows to tables. Not tables to databases, or columns to tables, but rows to tables.
From what I can tell, you have two tables connected using a foreign key constraint:
create table users (
user_id int auto_increment primary key,
phone_number varchar(255),
password varchar(255), -- should be encrypted
name varchar(255)
);
create table user_daily (
user_daily_id int auto_increment primary key,
user_id int,
current_date date,
current_capital numeric(10, 2),
current_percent numeric(5, 4),
constraint fk_user_daily_users foreign key (user_id) references users(user_id)
);
Note that both tables have auto-incrementing primary keys.

Relationships midst two tables?

I have table visitors and table users. Each visitor can be created by only one user and contains field visitors.userId.
So, any another user from table users can edit or delete one or more visitors.
I have created a third table events_log for logging actions like edit/delete:
Visitors_log
id | userId | visitorId | action
This table stores information about user who did actions over table visitors.
Which relationship should be between table visitors_log and rest two: users and visitors?
Now I have this Db scheme:
My opinion is: visitors_log can have one or more rows. So relations is one to many. In the same time visitors_log can contain one or more users. So, where I am wrong? Now it is one to one relation.
Is there a possibility that the user_id of a visitor could ever change ?
If the answer is yes, then you would better take the safe approach and have two foreign keys in the log, referencing the concerned visitor and the user that commited the action.
In MySQL :
CREATE TABLE visitors_log (
idVisitorLog INT AUTO_INCREMENT,
idVisitor INT NOT NULL,
idUser INT NOT NULL,
action VARCHAR(100) NOT NULL,
date_action DATETIME NOT NULL,
PRIMARY KEY (idVisitorLog),
FOREIGN KEY (visitor_log_idVisitor) REFERENCES visitors(idVisitor),
FOREIGN KEY (visitor_log_idUser) REFERENCES users(idUser)
);
PS : you probably want a date column too in the log table, I added one.
On the other hand, if the user a visitor is assigned to can never change over time, then your design can be simplified. In the log table, you could just store a foreign key to the visitors table. As the visitor stores a (fixed) user id, you do not need to duplicate that information in the log.

how to create sql table with foreign keys

I am wanting to create a sqlDB on my server, I am very new to db development and have only done the odd bit of coding here an there several years ago. I am trying to build a db that has four tables that reference each other..
This is what each of the tables are created for to give you a better idea as to what I am trying to achieve.
Group
this table will store hubs which users create for other users to follow.
User
stores users details which are used when creating groups and joining groups
//Not sure if this next one is a good idea but hopefully someone can let me know what they thing about it
userGroups
this table stores all or the groups and user connections. When a user joins a group their id is stored with the group id.
Countries
countries are used to help restrict the number of results that can be returned
heres the code I have created that I would like to run on my DB.. I am not sure if I have made the foreign keys correctly, any advice on that would be appreciated also.
CREATE DATABASE tempDB
USE tempDB
CREATE TABLE Group (groupID UInt32 PRIMARY KEY, userID UInt32 references User(SID), country VARCHAR(20) references Country(SID));
CREATE TABLE User (userID UInt32 PRIMARY KEY, name VARCHAR(20), country VARCHAR(20) references Country(SID));
CREATE TABLE userGroups (userID references User(SID), groupID UInt32 references Group(SID));
CREATE TABLE countries (countryName VARCHAR(20) PRIMARY KEY);
so three questions:
Is the table UserGroups worth while?
Have I created the foreign Keys correctly?
Will this code create a DB with the 4 tables in them...
If your users can be in many groups and many users can be in a group drop the column and foreign key reference to the userid field in the group table. The usergroups table handles this many-to-many mapping.
Your current setup would only make sense if say each group had also a single 'owner' user...
Also, what DB engine are you using? Innodb or myisam... If myisam foreign keys are jest like any other index without any ability to enforce constraints, therefore not really useful to try and declare.
Before creating any table which has a foreign key that table should be created.
Country(SID)- there is no table Country and field SID
Countries table should have a id field as primary key.
To use foreign keys you should specify the engine =INNODB
To check if tables have been created with Forign key
mysql> Show tables // Shows all created table
mysql> desc tableName // to see the structure of the created table

Multiple possible relationships on table

I have a table that contains account information for various entities in the database. Currently the table design is something like:
CREATE TABLE account (id int(11) NOT NULL auto_increment,
account_id int(11) NOT NULL,
account_type varchar(15) NOT NULL,
balance decimal(12,2) NOT NULL,
PRIMARY KEY (id))
The account_id column references (not database enforced) one of 3 tables. The account_type column tells the programmer which table to reference. I do not like this approach, because I cannot enforce the relationship and the programmers can accidentally corrupt the data. I have considered doing one of the following:
Adding a nullable foreign key for each type, or dropping the account_id column and adding a cross reference table to link the account to the entities. The account_type column would be used to tell the programmers which cross reference table to access. Are there any other options? What is the best practice for something like this?
You could try having a master identity table from which the three shared-identity tables draw their primary keys. Your account table in the question would then link to the master table. Loosely described:
MasterIdentity
Id (autoincrement)
IdentityType (string, maybe FK to a type lookup table, whatever you want)
Table1
Id (PK, FK to MasterIdentity)
other data
Table2
Id (PK, FK to MasterIdentity)
other data
Table3
Id (PK, FK to MasterIdentity)
other data
Account
Id (its own identifier as you already have)
AccountID (FK to MasterIdentity)
other data
Inserting into any of the three tables would involve inserting into MasterIdentity, grabbing the scope identity value from the insert, and inserting into the desired table directly specifying the Id. (This would all have to be atomic within a transaction, of course.) Note that the Id on the three tables are not auto-increment values, you'd provide them.
Then any table which needs to refer to those three (non-overlapping, I assume) tables would have a single table to refer to which has the identity and the type, the latter of which tells you which sub-table has the rest of that record's data.
(I'm pretty sure this is called a supertype/subtype table relationship, but I can't say for certain.)