One field with two references in MySQL - mysql

I have three tables:
CREATE TABLE Address (
ResidentID CHAR(5) NOT NULL,
Location varchar(255) NOT NULL,
KEY ResidentID(ResidentID)
);
CREATE TABLE Customer (
CustomerID CHAR(5) NOT NULL,
ContactName varchar(40) NOT NULL,
PRIMARY KEY (CustomerID)
);
CREATE TABLE Supplier (
SupplierID CHAR(5) NOT NULL,
SupplierName varchar(40) NOT NULL,
PRIMARY KEY (SupplierID)
);
I want to store CustomerID and SupplierID in the Address.ResidentID field with using of foreign keys:
ALTER TABLE Address ADD CONSTRAINT fk_CustomerID1 FOREIGN KEY(ResidentID) REFERENCES Customer(CustomerID);
ALTER TABLE Address ADD CONSTRAINT fk_SupplierID1 FOREIGN KEY(ResidentID) REFERENCES Supplier(SupplierID);
But second 'ALTER TABLE' raises Error: relation already exists
Any suggestions?
Data example:
CustomerID ContactName
C0001 Den
SupplierID ContactName
S0001 John
So Address table should contains:
ResidentID Location
C0001 Alaska
S0001 Nevada

You need to either reference addresses from the Customer / Supplier (if they only have one) or two different columns.
The reason you see in this SQLFiddle You cannot INSERT the required columns into the Address table if the ResidentID references BOTH tables. You could only insert lines that would match the contents of Customer AND Supplier but you want an OR connection that you can't create that way.
(Note: In my solutions I assume addresses to be optional. As Tom pointed out in the comments that may not be what you wanted, or expected. Make sure to mark the FK Columns in the first solution as NOT NULL if you want addresses to be mandatory, its more complicated for the second one. You have to mind the correct insertion order then.)
Either:
CREATE TABLE Address (
AddressID CHAR(5) NOT NULL,
Location varchar(255) NOT NULL,
PRIMARY KEY (AddressID)
);
CREATE TABLE Customer (
CustomerID CHAR(5) NOT NULL,
AddressID CHAR(5),
ContactName varchar(40) NOT NULL,
PRIMARY KEY (CustomerID)
);
CREATE TABLE Supplier (
SupplierID CHAR(5) NOT NULL,
AddressID CHAR(5),
SupplierName varchar(40) NOT NULL,
PRIMARY KEY (SupplierID)
);
ALTER TABLE Customer ADD CONSTRAINT fk_AddressID_Cust FOREIGN KEY(AddressID) REFERENCES Address(AddressID);
ALTER TABLE Supplier ADD CONSTRAINT fk_AddressID_Supp FOREIGN KEY(AddressID) REFERENCES Address(AddressID);
or
CREATE TABLE Address (
CustomerID CHAR(5),
SupplierID CHAR(5),
Location varchar(255) NOT NULL,
PRIMARY KEY (CustomerID, SupplierID)
);
CREATE TABLE Customer (
CustomerID CHAR(5) NOT NULL,
ContactName varchar(40) NOT NULL,
PRIMARY KEY (CustomerID)
);
CREATE TABLE Supplier (
SupplierID CHAR(5) NOT NULL,
SupplierName varchar(40) NOT NULL,
PRIMARY KEY (SupplierID)
);
ALTER TABLE Address ADD CONSTRAINT fk_CustomerID1 FOREIGN KEY(CustomerID) REFERENCES Customer(CustomerID);
ALTER TABLE Address ADD CONSTRAINT fk_SupplierID1 FOREIGN KEY(SupplierId) REFERENCES Supplier(SupplierID);

The approach you're trying is (a) not possible and (b) undesirable even if it was possible.
The best approach is to have a CustomerAddress table and a SupplierAddress table, each with a single FK to the matching base table; or if you must, a cross-reference table with appropriate constraints.
If your motivation for having a single Address table was code reuse, you can still do that ... think in terms of a template xxxAddress table design that can refer to any base xxx table. You can write non-database code that treats the base table name as a parameter and then could handle any number of xxxAddress tables as you add more base tables over time.
Or if your motivation for having a single Address table was to simplify reporting, you can always create a view or stored proc that returns a union of all such tables + an added field to indicate the base table for each address row.
Angelo I am revising this a bit based on your comment ---
Angelo, I ran your sample code in a local MySQL instance (not SQLFiddle) and observed an error.
I was surprised (you learn something every day) that MySQL did allow two foreign key constraints to be defined on the same field; however when you attempt to insert data, when trying to point the FK to the Customer table, I get an error saying a foreign key constraint fails referencing the Supplier table; and vice versa for the insert trying to point the FK to the Supplier table.
So my revised statement is (a) it is possible to create the hydra-headed FK in at least some DBMSs -- verified in MySQL, MS SQL Server and Oracle -- although (b) this only makes sense to use when the foreign key can refer to the same logical entity by ID across multiple tables (e.g. to ensure there is a corresponding record in all required tables, for example); and (c) if used to refer to multiple tables where the primary key is NOT the same logical entity, only works if by chance the same primary key value just happens to exist in all referenced tables, which is likely to lead to subtle, hard-to-find errors.
In other words, your example would work when attempting to insert a record referring to Customer ID=3 only if there was also a Supplier ID=3, which are really logically unrelated.
So my slightly revised answer to the OP is, what you're trying to do is not possible (or logical) when the foreign key is referring to different ENTITIES, as in the OP example of Customers and Suppliers.

Related

Which database scheme is better for performance aspect?

----Scheme1----
CREATE TABLE college (
id INT AUTO_INCREMENT,
name VARCHAR(250) NOT NULL,
address VARCHAR(250),
PRIMARY KEY (id)
);
CREATE TABLE student (
college INT NOT NULL,
username VARCHAR(50) NOT NULL,
name VARCHAR(100),
FOREIGN KEY (college) REFERENCES college(id),
CONSTRAINT pk PRIMARY KEY (college,username)
);
CREATE TABLE subject (
college INT NOT NULL,
id INT NOT NULL,
name VARCHAR(100),
FOREIGN KEY (college) REFERENCES college(id),
CONSTRAINT pk PRIMARY KEY (college,id)
);
CREATE TABLE marks (
college INT NOT NULL,
student VARCHAR(50) NOT NULL,
subject INT NOT NULL,
marks INT NOT NULL,
// forget about standard for this example
FOREIGN KEY (college) REFERENCES college(id),
FOREIGN KEY (student) REFERENCES student(username),
FOREIGN KEY (subject) REFERENCES subject(id),
CONSTRAINT pk PRIMARY KEY (college,subject,student)
);
----Scheme2----
CREATE TABLE college (
id INT AUTO_INCREMENT,
name VARCHAR(250) NOT NULL,
address VARCHAR(250),
PRIMARY KEY (id)
);
CREATE TABLE student (
college INT NOT NULL,
id BIGINT NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
name VARCHAR(100),
FOREIGN KEY (college) REFERENCES college(id),
PRIMARY KEY (id)
);
CREATE TABLE subject (
college INT NOT NULL,
id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(100),
FOREIGN KEY (college) REFERENCES college(id),
PRIMARY KEY (id)
);
CREATE TABLE marks (
student VARCHAR(50) NOT NULL,
subject INT NOT NULL,
id BIGINT NOT NULL AUTO_INCREMENT,
marks INT NOT NULL,
// forget about standard for this example
FOREIGN KEY (student) REFERENCES student(id),
FOREIGN KEY (subject) REFERENCES subject(id),
PRIMARY KEY (id)
);
Looking at the above database schemes it looks like Scheme1 will give better performance while searching for the result of a specific student and faster in filtering results but it feels like it is not in all normalized forms. While Scheme2, on the other hand, looks to be fully normal but might require more JOIN operations to fetch certain results or filter the data.
Please tell me if I'm wrong about my Schemes here, also tell me which one is better?
I would go for Schema 2: when it comes to reference a table, it is easier done by using a single column (auto_incremented primary key in Schema 1) than a combination of columns (coumpound primary keys in Schema 1). Also, as commented by O.Jones, Schema 2 assumes that two students in the same college cannot have the same name, which does not seem sensible.
There are other issues with Schema 1, eg the foreign key that relates the marks to students is malformed (you would need a coumpound foreign keys that include the college id instead of just the student name).
With properly defined foreign keys referencing primary keys, performance will not be a problem; joins perform good in this situation.
But one flaw should be fixed in Schema 2, that is to store a reference to the college in the marks table. You don't need this, since a student belongs to a college (there is a reference to the college in the student table).
Also, I am unsure that a subject should belong to a college: isn't it possible that the same subject would be taught in different colleges?
Finally, I would suggest giving clearer names to the foreign key columns, like student_id instead of student, and college_id instead of college.
It's difficult to assess whether a schema is normalized without first knowing the the relationships between entities. Can a student be associated with only one college? Can a student be associated multiple times over with the same subject, getting different marks?
Declaring foreign keys maintains referential integrity but slows down insertions and updates. You can get the same functionality without declaring the fks, but you may end up with some orphaned records. The fact that a particular index is used for a fk, or not, makes no difference to SELECT query performance.
JOIN operations use indexes. So do fks. So if you have the correct indexes, your JOIN operations will be efficient. But it's impossible to know which indexes are the best without knowing your JOIN queries.
Conventionally, each table's id column comes first. And many designers name each id column after the table in which it appears, for example college.college_id rather than college.id. That makes JOIN queries slightly easier to read.
You should use a surrogate primary key in the student table (student.student_id) rather than using the student's name as part of the primary key. JOINing on id values is faster than joining on VARCHAR() values. And, some students may share names. (In the real world, peoples's dates of birth accompany their names in tables: it helps tell people apart.)
I think your marks table should contain these columns:
CREATE TABLE marks (
student_id INT NOT NULL,
subject_id INT NOT NULL,
marks INT NOT NULL,
// foreign keys as needed
PRIMARY KEY (student_id, subject_id)
);
Can a student have multiple marks for the same subject? In that case use a marks_id as the pk instead of (student_id, subject_id).

How we can use the primary key in another table

I have Two table
customer table which has contained the information of the customer. But it has an account number we make a primary key of the account number.
And now the second Table is Bill Table.I've use the account number of the customer table when we update some information about the Bill table then will update is automatically of the particular account number
so, please tell me how we can resolve this problem, and how we can use
the foreign key of Bill table
I think what you are asking is how to update the Customer table at the same time when you are updating Bill table.
You can easily use a stored procedure to achieve this task. Within the stored procedure you can use transactions to make sure the 2nd update happens only if the first update is succeded. Otherwise, you can rollback.
So imagine that this is your customer table:
CREATE TABLE customer (
AccountNum int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (AccountNum)
);
PRIMARY KEY (AccountNum) > so you have a primary key in that table. Kudos!
CREATE TABLE BillTable (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
AccountNum int NOT NULL,
PRIMARY KEY (OrderID),
FOREIGN KEY (AccountNum) REFERENCES customer(AccountNum)
);
Now you linked customer and BillTable.

MySQL : Error Code 1215 : Cannot add foreign key constraint

I'm trying to make a simple SQL schema, but I'm having some problem with defining foreign keys. I really don't have that much MySQL knowledge, so I thought I'd ask her for some help. I get Error Code 1215 when I try to create the foreign key roomID and 'guestEmail' in the HotelManagement.Reservation table creation.
CREATE database HotelManagement;
CREATE TABLE HotelManagement.Room (
roomID INT not null auto_increment,
roomTaken TINYINT(1),
beds INT not null,
size INT not null,
roomRank INT not null,
PRIMARY KEY(roomID));
CREATE TABLE HotelManagement.HotelTask (
taskType INT not null,
taskStatus TINYINT(1) not null,
whichRoom INT not null,
note VARCHAR(255),
PRIMARY KEY (taskType),
FOREIGN KEY (whichRoom) REFERENCES HotelManagement.Room(roomID));
CREATE TABLE HotelManagement.Guest (
firstName varchar(25) not null,
lastName varchar(25) not null,
userPassword varchar(25) not null,
email varchar(25) not null,
reservation INT,
PRIMARY KEY (userPassword, email));
CREATE TABLE HotelManagement.Reservation (
reservationID INT not null,
id_room INT not null,
guestEmail varchar(25) not null,
fromDate DATE not null,
toDate DATE not null,
PRIMARY KEY (reservationID),
FOREIGN KEY (guestEmail)
REFERENCES HotelManagement.Guest(email),
FOREIGN KEY (id_room)
REFERENCES HotelManagement.Room(roomID)
);
ALTER TABLE HotelManagement.Guest
ADD CONSTRAINT res_constr FOREIGN KEY (reservation)
REFERENCES HotelManagement.Reservation(reservationID);
Updated the .sql
In the hoteltask table you have already defined a foreign key named roomid. Foreign key names also have to be unique, so just give a different name to the 2nd foreign key or omit the name completely:
If the CONSTRAINT symbol clause is given, the symbol value, if used,
must be unique in the database. A duplicate symbol will result in an
error similar to: ERROR 1022 (2300): Can't write; duplicate key in
table '#sql- 464_1'. If the clause is not given, or a symbol is not
included following the CONSTRAINT keyword, a name for the constraint
is created automatically.
UPDATE
The email field in the guest table is the rightmost column of the primary key, this way the pk cannot be used to independently look up email in that table. Either change the order or fields in the pk, or have a separate index on email field in the guest table. Quote from the same link as above:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Pls read through the entire documentation I linked before proceeding with creating the fks!
Side note 2 (1st is in the comments below): you should probably have a unique numeric guest id because that is lot more efficient than using email. Even if you decide to stick with email as id, I would restrict the pk in the guest table to email only. With the current pk I can register with the same email multiple times if I use different password.

Splitting two large de-normalised tables into multiple tables with link tables

This is my first stackoverflow question so I'm very sorry if I haven't got the question-asking etiquette right.
I have two very messy large tables called Centres and Contacts - one has company and address data, and the other has contact, company and address data:
Centres:
-CompanyGUID (PK)
-CompanyName
-MainTelephone
-MainEmail
-Address1
-Address2
-Town
-Postcode
Notes
Contacts:
-ContactID (PK)
-FirstName
-LastName
-CompanyName
-Telephone
-Email
-Address1
-Address2
-Town
-Postcode
-Notes
I am trying to move this data into a new normalised database that has separate tables for contacts, companies and addresses and linking tables between each of these to allow for many-to-many relationships between all three tables:
Companies:
-CompanyGUID
-CompanyName
-MainTelephone
-MainEmail
-Notes
Contacts:
-FirstName
-LastName
-Telephone
-Email
-Notes
Addresses:
-Address1
-Address2
-Town
-Postcode
There are many more columns in the tables but this is enough to demonstrate the problem. Many of the companies and addresses are the same in both tables, but not necessarily.
I need to maintain the existing relationships between contacts, companies and addresses while removing the redundancy and allowing for many-to-many relationships between companies and addresses (companies_addresses link table) and contacts and companies (companies_contacts link table).
I have seen a few examples splitting one table into two destination tables but I have three, plus two link tables. Is this possible? what approach would you take?
many thanks in advance to anyone who can help.
I think what you propose with the five tables (companies, contacts, addresses, companies_addresses, companies_contacts) is just fine.
I wonder whether you really have many-to-many relationship between addresses and companies. The original table centres suggests only one (main?) address for a company. If that's the case, skip companies_addresses table and add a foreign key in table companies. On the other hand, in your data you might have the many-to-many relationship.
You may want to keep the association between contact and their address. (Perhaps you don't need this. I'm just speculating.) In that case, you will need a link table between companies_addresses and contacts table instead of companies_contacts table: the contact would be associated with a specific address and a company.
Hope this helps.
The SQL for this solution would be like this:
-- tables
-- Table addresses
CREATE TABLE addresses (
addressId int NOT NULL,
address1 varchar(255) NOT NULL,
address2 varchar(255) NOT NULL,
town varchar(255) NOT NULL,
postcode varchar(255) NOT NULL,
CONSTRAINT addresses_pk PRIMARY KEY (addressId)
);
-- Table companies
CREATE TABLE companies (
companyGUID int NOT NULL,
companyName varchar(255) NOT NULL,
CONSTRAINT companies_pk PRIMARY KEY (companyGUID)
);
-- Table companies_addresses
CREATE TABLE companies_addresses (
companies_companyGUID int NOT NULL,
addresses_addressId int NOT NULL,
CONSTRAINT companies_addresses_pk PRIMARY KEY (companies_companyGUID,addresses_addressId)
);
-- Table contacts
CREATE TABLE contacts (
contactID int NOT NULL,
firstName varchar(255) NOT NULL,
lastName varchar(255) NOT NULL,
CONSTRAINT contacts_pk PRIMARY KEY (contactID)
);
-- Table contacts_companies_addresses
CREATE TABLE contacts_companies_addresses (
contacts_contactID int NOT NULL,
companies_addresses_companies_companyGUID int NOT NULL,
companies_addresses_addresses_addressId int NOT NULL,
CONSTRAINT contacts_companies_addresses_pk PRIMARY KEY (contacts_contactID,companies_addresses_companies_companyGUID,companies_addresses_addresses_addressId)
);
-- foreign keys
-- Reference: Table_5_contacts (table: contacts_companies_addresses)
ALTER TABLE contacts_companies_addresses ADD CONSTRAINT Table_5_contacts FOREIGN KEY Table_5_contacts (contacts_contactID)
REFERENCES contacts (contactID);
-- Reference: companies_addresses_addresses (table: companies_addresses)
ALTER TABLE companies_addresses ADD CONSTRAINT companies_addresses_addresses FOREIGN KEY companies_addresses_addresses (addresses_addressId)
REFERENCES addresses (addressId);
-- Reference: companies_addresses_companies (table: companies_addresses)
ALTER TABLE companies_addresses ADD CONSTRAINT companies_addresses_companies FOREIGN KEY companies_addresses_companies (companies_companyGUID)
REFERENCES companies (companyGUID);
-- Reference: contact_companies_addresses (table: contacts_companies_addresses)
ALTER TABLE contacts_companies_addresses ADD CONSTRAINT contact_companies_addresses FOREIGN KEY contact_companies_addresses (companies_addresses_companies_companyGUID,companies_addresses_addresses_addressId)
REFERENCES companies_addresses (companies_companyGUID,addresses_addressId);

Can a table have two foreign keys?

I have the following tables (Primary key in bold. Foreign key in Italic)
Customer table
ID---Name---Balance---Account_Name---Account_Type
Account Category table
Account_Type----Balance
Customer Detail table
Account_Name---First_Name----Last_Name---Address
Can I have two foreign keys in the Customer table and how can I implement this in MySQL?
Updated
I am developing a web based accounting system for a final project.
Account Category
Account Type--------------Balance
Assets
Liabilities
Equity
Expenses
Income
Asset
Asset_ID-----Asset Name----Balance----Account Type
Receivable
Receivable_ID-----Receivable Name-------Address--------Tel-----Asset_ID----Account Type
Receivable Account
Transaction_ID----Description----Amount---
Balance----Receivable_ID----Asset_ID---Account Type
I drew the ER(Entity relationship) diagram using a software and when I specify the relationship it automatically added the multiple foreign keys as shown above. Is the design not sound enough?
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
Yes, MySQL allows this. You can have multiple foreign keys on the same table.
Get more details here FOREIGN KEY Constraints
The foreign keys in your schema (on Account_Name and Account_Type) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.
There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.
Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.
CREATE TABLE User (
user_id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
userImage LONGBLOB NOT NULL,
Favorite VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);
and
CREATE TABLE Event (
EventID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (EventID),
EventName VARCHAR(100) NOT NULL,
EventLocation VARCHAR(100) NOT NULL,
EventPriceRange VARCHAR(100) NOT NULL,
EventDate Date NOT NULL,
EventTime Time NOT NULL,
EventDescription VARCHAR(255) NOT NULL,
EventCategory VARCHAR(255) NOT NULL,
EventImage LONGBLOB NOT NULL,
index(EventID),
FOREIGN KEY (EventID) REFERENCES User(user_id)
);