Adding external IDs to primary key field - ms-access

I am creating a database for a university dept(for internal use) and this database tracks issues related to people. I get information of only employees at the university and I am tracking them using their university ID. But the database is also intended for people who are not employees at the university or even sometimes people outside the university. I want to assign an ID to these people but store values within same column as university id. Any ideas how I should tackle this issue? I don't know how to keep the univ id and the no. I am going to give to the others in the same column and yet treat them differently (when needed). How do people usually tackle such issues?
PS: I do not like auto numbers since I cannot delete an ID and get it back into the database

Your best bet here is probably to create a common Person table for all people which simply tracks an Id, then relate separate tables for each of the different kinds of people (ex. Employee, Student, etc.) to it - note that all of these names are just examples. Each of these tables would contain a foreign key to the Person table. In effect, this logically make each of them a different "subclass" of person.
For example, Employee my be related to Person via the foreign key
[Person.PersonId] {PK} <==(1-0)==> {FK:Person.PersonId} Employee.PersonId
This is generic for any Other entity:
[Person.PersonId] {PK} <==(1-0)==> {FK:Person.PersonId} Other.PersonId
Note that any columns common to all types of person may exist directly on the Person table, with each of the "subclasses" of person only recording columns specific to its particular type.
In addition, you may create a view with joins these tables to present a "combined" generic record for people. In some cases, it's useful to include a column in the view that simply indicates which table an individual record came from (ex, class or type.

I personally would not want to mix the two different kind of ids within one field. This is just waiting for trouble when you migrate since you need to keep these apart by convention or through other fields.
You will of course use the uni id to search the person ...
(uni id and an id for people not on uni)
Approach 1 - introduce an additional table
Issue
- id
- person_id
Person
- id
- university_person_id (optional)
University Person (table)
- id
Approach 2 - make the university ref id optional
Issue
- person_id
Person
- id
- university_ref (optional)
What do you think?
But if you really want to go along with mixing the two kind of ids within one field I suggest to use a prefix followed by a generated number.
EXTERNAL-123456
You can also introduce an additional field external_contact (boolean) or contact_type 'Uni' or 'External'. Also add a unique index on the two combined.
Hope this will give you some food for thought :)

Related

MySQL Database Layout/Modelling/Design Approach / Relationships

Scenario: Multiple Types to a single type; one to many.
So for example:
parent multiple type: students table, suppliers table, customers table, hotels table
child single type: banking details
So a student may have multiple banking details, as can a supplier, etc etc.
Layout Option 1 students table (id) + students_banking_details (student_id) table with the appropriate id relationship, repeat per parent type.
Layout Option 2 students table (+others) + banking_details table. banking_details would have a parent_id column for linking and a parent_type field for determining what the parent is (student / supplier / customers etc).
Layout Option 3 students table (+others) + banking_details table. Then I would create another association table per parent type (eg: students_banking_details) for the linking of student_id and banking_details_id.
Layout Option 4 students table (+others) + banking_details table. banking_details would have a column for each parent type, ie: student_id, supplier_id, customers_id - etc.
Other? Your input...
My thoughts on each of these:
Multiple tables of the same type of information seems wrong. If I want to change what gets stored about banking details, thats also several tables I have to change as opposed to one.
Seems like the most viable option. Apparently this doesnt maintain 'referential integrity' though. I don't know how important that is to me if I'm just going to be cleaning up children programatically when I delete the parents?
Same as (2) except with an extra table per type so my logic tells me this would be slower than (2) with more tables and with the same outcome.
Seems dirty to me with a bunch of null fields in the banking_details table.
Before going any further: if you do decide on a design for storing banking details which lacks referential integrity, please tell me who's going to be running it so I can never, ever do business with them. It's that important. Constraints in your application logic may be followed; things happen, exceptions, interruptions, inconsistencies which are later reflected in data because there aren't meaningful safeguards. Constraints in your schema design must be followed. Much safer, and banking data is something to be as safe as possible with.
You're correct in identifying #1 as suboptimal; an account is an account, no matter who owns it. #2 is out because referential integrity is non-negotiable. #3 is, strictly speaking, the most viable approach, although if you know you're never going to need to worry about expanding the number of entities who might have banking details, you could get away with #4 and a CHECK constraint to ensure that each row only has a value for one of the four foreign keys -- but you're using MySQL, which ignores CHECK constraints, so go with #3.
Index your foreign keys and performance will be fine. Views are nice to avoid boilerplate JOINs if you have a need to do that.

Normalize two tables with same primary key to 3NF

I have two tables currently with the same primary key, can I have these two tables with the same primary key?
Also are all the tables in 3rd normal form
Ticket:
-------------------
Ticket_id* PK
Flight_name* FK
Names*
Price
Tax
Number_bags
Travel class:
-------------------
Ticket id * PK
Customer_5star
Customer_normal
Customer_2star
Airmiles
Lounge_discount
ticket_economy
ticket_business
ticket_first
food allowance
drink allowance
the rest of the tables in the database are below
Passengers:
Names* PK
Credit_card_number
Credit_card_issue
Ticket_id *
Address
Flight:
Flight_name* PK
Flight_date
Source_airport_id* FK
Dest_airport_id* FK
Source
Destination
Plane_id*
Airport:
Source_airport_id* PK
Dest_airport_id* PK
Source_airport_country
Dest_airport_country
Pilot:
Pilot_name* PK
Plane id* FK
Pilot_grade
Month
Hours flown
Rate
Plane:
Plane_id* PK
Pilot_name* FK
This is not meant as an answer but it became too long for a comment...
Not to sound harsh, but your model has some serious flaws and you should probably take it back to the drawing board.
Consider what would happen if a Passenger buys a second Ticket for instance. The Passenger table should not hold any reference to tickets. Maybe a passenger can have more than one credit card though? Shouldn't Credit Cards be in their own table? The same applies to Addresses.
Why does the Airport table hold information that really is about destinations (or paths/trips)? You already record trip information in the Flights table. It seems to me that the Airport table should hold information pertaining to a particular airport (like name, location?, IATA code et cetera).
Can a Pilot just be associated with one single Plane? Doesn't sound very likely. The pilot table should not hold information about planes.
And the Planes table should not hold information on pilots as a plane surely can be connected to more than one pilot.
And so on... there are most likely other issues too, but these pointers should give you something to think about.
The only tables that sort of looks ok to me are Ticket and Flight.
Re same primary key:
Yes there can be multiple tables with the same primary key. Both in principle and in good practice. We declare a primary or other unique column set to say that those columns (and supersets of them) are unique in a table. When that is the case, declare such column sets. This happens all the time.
Eg: A typical reasonable case is "subtyping"/"subtables", where entities of a kind identified by a candidate key of one table are always or sometimes also of the kind identifed by the same values in another table. (If always then the one table's candidate key values are also in the other table's. And so we would declare a foreign key from the one to the other. We would say the one table's kind of entity is a subtype of the other's.) On the other hand sometimes one table is used with attributes of both kinds and attributes inapplicable to one kind are not used. (Ie via NULL or a tag indicating kind.)
Whether you should have cases of the same primary key depends on other criteria for good design as applied to your particular situation. You need to learn design including normalization.
Eg: All keys simple and 3NF implies 5NF, so if your two tables have the same set of values as only & simple primary key in every state and they are both in 3NF then their join contains exactly the same information as they do separately. Still, maybe you would keep them separate for clarity of design, for likelihood of change or for performance based on usage. You didn't give that information.
Re normal forms:
Normal forms apply to tables. The highest normal form of a table is a property independent of any other table. (Athough you might choose that form based on what forms & tables are alternatives.)
In order to normalize or determine a table's highest normal form one needs to know (in general) all the functional dependencies in it. (For normal forms above BCNF, also join dependencies.) You didn't give them. They are determined by what the meaning of the table is (ie how to determine what rows go in it in any given situation) and the possible situtations that can arise. You didn't give them. Your expectation that we could tell you about the normal forms your tables are in without giving such information suggests that you do not understand normalization and need to educate yourself about it.
Proper design also needs this information and in general all valid states that can arise from situations that arise. Ie constraints among given tables. You didn't give them.
Having two tables with the same key goes against the idea of removing redundancy in normalization.
Excluding that, are these tables in 1NF and 2NF?
Judging by the Names field, I'd suggest that table1 is not. If multiple names can belong to one ticket, then you need a new table, most likely with a composite key of ticket_id,name.

What is the Best Practice for Composite Key with JPA?

I am creating a DB for my project and I am facing a doubt regarding best practice.
My concrete case is:
I have a table that stores the floors of a building called "floor"
I have a second table that stores the buildings called "building"
I have a third table that stores the relationship between them, called building_x_floor
The problem is this 3rd table.
What should I do?
Have only two columns, one holding a FK to the PK of building and another holding an FK to the PK of floor;
Have the two columns above and a third column with a PK and control consistency with trigger, forbidding to insert a replicated touple of (idbuilding, idfloor)?
My first thought was to use the first option, but I googling around and talking I heard that it is not always the best option.
So I am asking for guidance.
I am Using MySQL 5.6.17
You don't need third table. Because there is one-to-many relationship between building and floor.
So one building has many floors and a floor belongs to one building. Don't get things complicated. Even though you need a table with composite keys, you should be careful. You need to override equals and hashCode methods.
I am still not confortable with that approach. I am not saying it is wrong or innapropriate, very far from that. I am trying to understand how the informations would be organized and how performatic it would be.
If I have a 1:* relationship, like a student may be attending to more than one subject along its university course within a semester I would Have the 3rd table with (semester, idstudent, iddiscipline).
If I try to get rid of the join table my relationship would be made with a FK inside student table or inside subject table. And it does not make sense to do that because student table is a table for a set of information related with registering the info of a person while the discipline table holds the data of a discipline, like content, hours...it is more a parametric table.
So I would need a table for the join.

Type-based database design

I want to rate (Very Good, Good, Medium, Bad...) 2 objects: Student and Teacher. Which design solution is better?
Solution 1:
Students(StudentID, Rating,...)
-----------------1--------Good-----
-----------------2--------Bad-----
-----------------3-----Very Good-----
Teachers(TeacherID, Rating,...)
-----------------1-----Very Good-----
-----------------2--------Bad-----
-----------------3--------Bad-----
Solution 2:
Students(StudentID, RatingTypeID,...)
-----------------1----------------2----------
-----------------2----------------1----------
-----------------3----------------3----------
Teachers(TeacherID, RatingTypeID,...)
-----------------1----------------1----------
-----------------2----------------1----------
-----------------3----------------3----------
RatingType(RatingID, RatingDescription,...)
-----------------1-------------Very Good---------
-----------------2---------------Good--------------
-----------------3----------------Bad---------------
If both of them are not good enough, can you give me some suggestions? Thanks!
Solution 2 is the best from those two, but if You want to have multiple votes in the course of your application's life, you should have a table where you identify what is the subject of the vote, and another where you store the votes:
Student:
id
name
class
...
Teacher:
id
name
subject
...
voterType
id
description (student or teacher)
contest:
id
description (ex: 1st Semester 2013)
contestVotes:
id
contestId
voterType (Teacher or Student)
voterId
ratingTypeId
Between the two suggested solutions, I would definitely choose the second one, for the following reasons:
Storing a Rating as a number can come handy in cases where ordering or aggregates are involved, in which cases a string is pretty much useless.
Making the Rating column a Foreign Key to the RatingType.RatingID enforces a constraint, that a Rating can only have values from a very specific set, with very specific meaning. Plus, you could potentially add extra columns to the RatingType table in the future, adding value to your ratings.
As for an improvement suggestion, since you asked, consider implementing this using IS-A relations. A teacher, as well as a student, are apparently both Persons and have common attributes to an extent. I would create a Person superclass table containing the common attributes (i.e. first name, last name, address, phone etc) and then make the primary keys of students and teachers also foreign keys to Persons.
Notice that, a rating is a common attribute too. So it's only natural to appear in the Persons table. Unless of course there are different types of ratings for teachers and students, in which case you would have to implement two different RatingType tables.

Shared Primary Key

I would guess this is a semi-common question but I can't find it in the list of past questions. I have a set of tables for products which need to share a primary key index. Assume something like the following:
product1_table:
id,
name,
category,
...other fields
product2_table:
id,
name,
category,
...other fields
product_to_category_table:
product_id,
category_id
Clearly it would be useful to have a shared index between the two product tables. Note, the idea of keeping them separate is because they have largely different sets of fields beyond the basics, however they share a common categorization.
UPDATE:
A lot of people have suggested table inheritance (or gen-spec). This is an option I'm aware of but given in other database systems I could share a sequence between tables I was hoping MySQL had a similar solution. I shall assume it doesn't based on the responses. I guess I'll have to go with table inheritance... Thank you all.
It's not really common, no. There is no native way to share a primary key. What I might do in your situation is this:
product_table
id
name
category
general_fields...
product_type1_table:
id
product_id
product_type1_fields...
product_type2_table:
id
product_id
product_type2_fields...
product_to_category_table:
product_id
category_id
That is, there is one master product table that has entries for all products and has the fields that generalize between the types, and type-specified tables with foreign keys into the master product table, which have the type-specific data.
A better design is to put the common columns in one products table, and the special columns in two separate tables. Use the product_id as the primary key in all three tables, but in the two special tables it is, in addition, a foreign key back to the main products table.
This simplifies the basic product search for ids and names by category.
Note, also that your design allows each product to be in one category at most.
It seems you are looking for table inheritance.
You could use a common table product with attributes common to both product1 and product2, plus a type attribute which could be either "product2" or "product1"
Then tables product1 and product2 would have all their specific attributes and a reference to the parent table product.
product:
id,
name,
category,
type
product1_table:
id,
#product_id,
product1_specific_fields
product2_table:
id,
#product_id,
product2_specific_fields
First let me state that I agree with everything that Chaos, Larry and Phil have said.
But if you insist on another way...
There are two reasons for your shared PK. One uniqueness across the two tables and two to complete referential integrity.
I'm not sure exactly what "sequence" features the Auto_increment columns support. It seem like there is a system setting to define the increment by value, but nothing per column.
What I would do in Oracle is just share the same sequence between the two tables. Another technique would be to set a STEP value of 2 in the auto_increment and start one at 1 and the other at 2. Either way, you're generating unique values between them.
You could create a third table that has nothing but the PK Column. This column could also provide the Autonumbering if there's no way of creating a skipping autonumber within one server. Then on each of your data tables you'd add CRUD triggers. An insert into either data table would first initiate an insert into the pseudo index table (and return the ID for use in the local table). Likewise a delete from the local table would initiate a delete from the pseudo index table. Any children tables which need to point to a parent point to this pseudo index table.
Note this will need to be a per row trigger and will slow down crud on these tables. But tables like "product" tend NOT to have a very high rate of DML in the first place. Anyone who complains about the "performance impact" is not considering scale.
Please note, this is provided as a functioning alternative and not my recommendation as the best way
You can't "share" a primary key.
Without knowing all the details, my best advice is to combine the tables into a single product table. Having optional fields that are populated for some products and not others is not necessarily a bad design.
Another option is to have a sort of inheritence model, where you have a single product table, and then two product "subtype" tables, which reference the main product table and have their own specialized set of fields. Querying this model is more painful than a single table IMHO, which is why I see it as the less-desirable option.
Your explanation is a little vague but, from my basic understanding I would be tempted to do this
The product table contains common fields
product
-------
product_id
name
...
the product_extra1 table and the product_extra2 table contain different fields
these tables habe a one to one relationship enforced between product.product_id and
product_extra1.product_id etc. Enforce the one to one relationship by setting the product_id in the Foreign key tables (product_extra1, etc) to be unique using a unique constraint.
you will need to decided on the business rules as to how this data is populated
product_extra1
---------------
product_id
extra_field1
extra_field2
....
product_extra2
---------------
product_id
different_extra_field1
different_extra_field2
....
Based on what you have above the product_category table is an intersecting table (1 to many - many to 1) which would imply that each product can be related to many categories
This can now stay the same.
This is yet another case of gen-spec.
See previous discussion