MySQL foreign key dependency resolution - mysql

I am modelling a relational database where the following schema is used to describe 2 tables: ERD Model.
The rules specified are that:
An office has a manager
Each staff member is assigned to an office
In order to model this I created an ERD using MySQL workbench, which provided the following DDL.
The issue I have is that in order to enforce that an office must have a manager, the foreign key in the office table is not nullable. Likewise, the foreign key in the staff table representing the office they work for is required for every staff and therefore not nullable. This makes sense to me in the model, however for the implementation it makes it impossible to insert data as each rely on the existance of tuples in the tables.
The only answer I can think of is to make the keys nullable such that one can temporarily exist without the other.
Is this the correct way to resolve the issue? The database will eventually be normalised to 3NF perhaps BCNF.

The problem is that you're attempting to record the relationship between offices and staff twice. Once in the office record and again in the staff record. You should only record the relationship in one place. Often this is done in a cross-reference table with two columns: Office_ID and Staff_ID. But it's also common to skip the third table and just record the relationship in one of the tables.
In this case, you can eliminate your problem by removing the Office field and foreign key from the Staff table. You'll be able to create as many Staff records as you need. Then when you create an Office record, you will be able to assign one of the Staff to the Office.

Related

Relating data from one table to another in mySQL

Here I have a EER diagram I am creating in the MySQL editor.
I want Person to relate to employee. I want some Persons entries to be employees/Customers/etc.
How would I implement this? Would it be a shared key? Join the tables? Related data?
I tried making EmployeeID a foreign key to PersonID. The tables still don't "relate". (There's no way to tell what employee X's name/dob/ect is.)
I encourage you to try again in the direction of making employeeID refer to personID, as a foreign key. You may not have implemented the whole idea.
The technique has a name: Shared Primary Key. If you search on this phrase, you will find articles describing what you have to do when adding a new employee. Without taking the correct steps when a new employee is added, you break the relationship between the two tables.
There is a tag with this name here in StackOverflow. shared-primary-key
What you are basically doing is setting up a situation where employee is a subclass of person. In an object-oriented system, this would be easy. SQL is not object oriented at the base level.

Identifying FK's in a MySQL database that were not defined upon database creation?

A database was created with 5 tables. These tables were populated with data upon creation - perhaps it was imported from a previous database.
When the DB was created, primary keys were created for each table, however foreign keys were not.
How do I run a query to identify which tables columns contain data that relates to the PK in other tables? Effectively, how do I identify the FK column(s) on each table? Some tables may contain 2 FK's.
The end goal is to identify the FK('s) in each table and properly set up the table with appropriate FK structure and table relations.
Don't try to use queries to automate this database design / reverse-engineering process. (If you had 500 tables, maybe. But you only have five.)
Eyeball your table definitions. If you have, for example, an id primary key column in your user table, your contact table might have a user_id column. That is the FK to user.id. It will help you greatly if you really understand how your tables tie together with FKs.
And, keep in mind that your system will still work tolerably well if you don't bother to actually declare these foreign keys. What you'll lose:
constraints, in which the database engine prevents, for example a contact.user_id column value that doesn't point to any user.id row.
possibly some helpful indexing.
MySql Workbench has a reverse engineering feature. It inspects the definition of a database and does its best to sort out various entities (tables) and the relationships (foreign key dependencies) between them. It presents graphical e:r diagrams and can generate DDL. That can help you understand a database and set up appropriate FKs. But still, check the relationships it suggests: this data is yours, not Workbench's.

How to create an IS_A relationship using Microsoft Access Relationships Tool

I was unable to find a clear answer of how to create an IS_A relationship in Access.
There was the same question here, but without a concise answer:
IS_A relationship primary key validation rules
I have the entity Employee, and two sub-entities Loan_Officer and Branch_Manager. It's a school example of an IS_A relationship really.
I've managed to create A relationship, but there needs to be a constraint that an employee must be either a Loan Officer or a Branch Manager, but can not be both. Now, I can't figure out how to do this, because what ever I do, I can assign the same Employee_ID in both sub-entity tables at once.
I've connected the tables via the PK, as it's shown here:
Now, this table design is just something I've done, in order to be able to connect them via a one-to-one relationship. I had to set the PK of Loan_Officer to "Number" and not "AutoNumber", in order to be able to connect them. The other option is to have a separate PK in Loan_Officer, like "Loan_Officer_ID", and a foreign key, "Employee_ID" in the Loan_Officer table, but the results are again the same (also according to the ER Diagram, the sub-entities don't have a separate PK).
You can't. This is not a feature of the Access database.
You can create CHECK constraints to check for such conditions, but those don't offer features to cascade operations.
See this answer for an example on how to create a CHECK constraint.
There is no such thing as an 'Is A' relationship in databases between tables. This is instead a field in the Employee table or Employee History Table.
The issue of 'can't be both' is a matter of validation logic. Where this validation logic is applied is probably at the form object level (during data entry), not the table level (no data should ever be entered directly into tables by end users).
Look into Access Data Macros . They can be used like SQL triggers firing off when a record is INSERTed, UPDATEed, DELETEed etc.

In MySQL, why do I have to define ForeignKey relationships?

Why can't I just leave those relationships out?
What's the point of them?
I can stil run queries and treat them like it a relationship myself...
Yes, you can always leave the foreign key constraints out but then you will be responsible about the integrity of your data. If you use foreign key constraints, then you won't have to worry about the referential integrity among tables. You can read more about referential integrity from Wikipedia. I will also try to explain it with an example below.
Think of a shopping cart scenario. You have three tables: item, shopping_cart and shopping_cart_item. You can choose not to define any relationship between these tables, that's fine for any SQL solution. When user starts shopping, you create a shopping cart by adding a shopping_cart entry. As user adds items to his shopping cart, you save this information by adding rows to shopping_cart_item table.
One problem may occur at this step: If you have a buggy code that assigns incorrect shopping_cart_id's to shopping_cart_items, then you will definitely end up with incorrect data! Yes, you can have this case even with a foreign key constraint if the assigned id actually exists in the shopping_cart table. But this error will be more detectable when a foreign key exists since it would not insert shopping_cart_item record when the foreign key constraint fails.
Let's continue with the assumption that your code is not buggy and you won't have first type of referential integrity. Then suddenly a user wants to stop shopping and delete the cart and you chose to implement this case by deleting the shopping_cart and shopping_cart_item entries. Then you will have to delete entries in both tables with two separate queries. If something goes wrong after you delete shopping_cart entries, then you will again have a referential integrity problem: You will have shopping_cart_items that are not related to any shopping_cart. You will then have to introduce transaction managing, try to provide meaningful data to your business logic about the error happened in data access layer, etc..
In this type of scenario's, foreign keys can save life. You can define a foreign key constraint that will prevent insertion of any sort of incorrect data and you can define cascade operations that will automatically perform deletion of related data.
If there is anything unclear, just leave a comment and I can improve the answer.
Apart from what the others have said about why you technically want (actually: need) them:
foreign key constraints also document your model.
When looking at a model without FK constraints you have no idea which table relates to which. But with FK constraints in place you immediately see how things belong together.
You create FOREIGN KEYs to instruct the database engine to ensure that you never perform an action on the database that creates invalid records.
So, if you create a FOREIGN KEY relationship between users.id and visits.userid the engine will refuse to perform any actions that result in a userid value in visits that does not exist in users. This might be adding an unknown userid to visits, removing an id from users that already exists in visits, or updating either field to "break" the relationship.
That is why PRIMARY and FOREIGN KEYs are referred to as referential integrity constraints. The tell your database engine how to keep your data correct.
It doesn't allow you to enter an id which does not exist in another table, for example, if you have products and you keep owner Id, by creating a foreign key ton the owner id to id field of the owners table, you do not allow users to create an object record which has an owner id which does not exist in the owner table. such things are called referential intergrity.
The foreign key constraint helps you ensure referential integrity.
If you delete a row in one table, mysql can automatically delete all rows in other tables that the deleted row refers to via the foreign key. You can also make it reject the delete command.
Also when you try to insert a row, mysql can automatically create new rows in other tables, so the foreign key does not refer to nothing.
That is what referential integrity is all about.
Databases can be affected by more than just the application. Not all data changes go through the application even if they are supposed to. People change stuff directly on the database all the time. Rules that need to apply to all data all the time belong on the database. Suppose you can update the prices of your stock. That's great for updating anindividual price. But what happens when the boss decides to raise all prices by 15%. No one is going to go through and change 10,000 prices one at a time through the GUI, they are going to write a quick SQL script to do the update. Or suppose two suppliers join together to have one company and you want to change all of thie items to be the new company. Those kinds of changes happen to databases every day and they too need to follow the rules for data integrity.
New developers may not know about all the places where the foreign key relationships should exist and thus make mistakes which cause the data to be no longer useful.
Databases without foreign key constraints have close to a 100% chance of having bad data in them. Do you really want to have orders where you can't identify who the customers were?
THe FKS will prevent you from deleting a customer who has orders for instance or if you use a natural key of company_name and the name changes, all related records must be changed with the key change.
Or suppose you decide to put a new GUI together and dump the old one, then you might have to figure out all the FK relationships again (because you are using a different datalayer or ORM) and the chances are you might miss some.
It is irresponsible in the extreme to not put in FK relationships. You are risking the lifeblood of your company's business because you think it is a pain to do. I'd fire you if you suggested not using FKs because I would know I couldn't trust my company's data to you.

security of rdbms

I am designing the human resource database for company ABC. and i want to deploy a relational model for the company database. Referring to the above scenario, how do you prevent users from changing the values in the primary table that results in orphaned records in a related table?
I suggest looking at Foreign Keys: http://en.wikipedia.org/wiki/Foreign_key