SQL Table primary key setting - sql

I'm trying to make a program that has to manage some databases with derby.
In this program, I'm creating two tables, one called "customers" (that has one primary key that is the ID number of the person), and one called "transactions", in which I want one column to reference to the ID of the customer, which I would do through a Foreign key. However, this customer could perform several transactions, so that the actual key would be a combination of the date of the transaction and the id of the customer. Can this be made through the foreign key? Or am I very confused? I would really appreciate any help you guys could give me.
Thanks a lot

It is best to also have a transaction ID. use that id column as the primary key in your transaction table, and have a foreign key user_id to relate to the user.id. Then you can uniquely identify each transaction, all transactions for a user, or query out other things like all transaction within a day for all users, for a set of users and so on.

Related

How to connect a primary key by primary key of the same table?

I want to construct this database. Here in category table we give ID primary key of the category table to foreign key of the category table. I understood this and I done this part also but see in product table we want to give ID primary key of the product table to product table as a primary key so how to do that? This is my question? We can't able to use the same syntax in the foreign key. I want to done this in SQL server. So kindly anyone help me to do this part.
The database looks ok apart from one thing:
One table, (product) has a 1:1-relation to itself. It makes no sense in any way.
1:1 relations are used between different tables and are great at times (customizations on 3:rd part systems etc)
What you probably want is a 1:n-relation to make one product act as a collection of other products, (also available as separate products). For this to work you must add a foregin-key field (nullable) in the product-table.
But that solution would probably be too limiting for the purpose above, since one product could only belong to one product. So what you want is a n:n relation. So what you need to do is create a new table as in:
product_part
============
product_id
part_product_id
This is called a junction table and both fields are used to make up the primary key.
However, junction tables may grow over time to regular tables as fields are added, so I would advice you to use a separate PK field (makes API-requests easier etc) as in:
product_part
============
id
product_id
part_product_id
position
qty
Hope this helps.

Multiple tables for a single foreign key

I'm currently making a database for my java web app for Tourism.
Only register user can book a tour but can take along several people.
For this, I separate into User table and Guest table, each with its own primary key.
Everything is set so far, but when it comes to making my BookRoomDetail table, I have to fill in which person for which slot in the room. the problem arises when both register user and guest can fill this slot, and they're from 2 different tables.
How do I set the foreign key(or anything else) for this?
As I got your problem, you can add one more field for MainUser in your tblBookRoom Detail as a foreign key. And whenever any user books room you can add his/her primary key and guest primary key in forwhom field.
**tblBookRoomDetail**
ID (Primary key Of Table)
RoomId
For Whom (For MainUser or Guest)
MainUser (MainUser Primary Key Who is doing this reservation)
Slot
FromDate
ToDate
BookId
This is not possible to insert two different primary key value in a column of other table, if you have relation in them.
You can do this without the making the relation in them.
But it's not a good process because if the both key value same in this case you can't identify the actual.
If you want to achieve this goal then you should have a table tblAllUsers which primary key is also primary key of the tblGuest and tblUser and then you can make relation to tblBookRoomDetail table direct to tblAllUsers. In this case you can differentiate the Guest user or Registered Users.
or
Can Create the two different columns in tblBookRoomDetail, one for Guest user and second for Registered user.

get confused in primary key concept and nomalisation

Let's take an example of a login table with the columns: id (primary key),username,password,status.
id is primary key but still we authenticate user by searching table through username+password. Doesn't it violate normalisation rule?
Another example: suppose we have two tables, employer and job
employer table's id is used injob table as foreign key but job table itself has its own id
job table
---------
id (primary key) || employer_id (foreign key) || etc etc
Now when we will search job posted by a employer we use employer_id but this table has its primary key?
Primary key on any table is an unique identifier and indexed by default. It does not mean that records will always be searched through that field itself. Now, when you are to link a parent record to a child record, you can use the primary key to establish the relationships.
While trying to get the records, you will make use of primary key as a link between different tables. For example, you have employers and employees. A search might look like: "Get me all the employees for this employer". Now, employer is the main entity here and we are looking for linked employee records for it. Here, employer id will help us fetch related records. A query for the same might appear something like this:
SELECT [COLUMN NAMES HERE]
FROM EMPLOYER INNER JOIN EMPLOYEE ON
EMPLOYER.ID = EMPLOYEE.EMPLOYERID
I suggest you to read some tutorial, but, shortly ... a primary key is an id that is unique and not null and identifies an entry in your table. A foreign key is a reference to an id in another table. As you said, employee and job tables. An id is in most cases generated by a sequence, you don't know its value before inserting the record.
You usually perform seraches through username, name, ... datas that are user-known. In your case, when you search for a job, you will probably perform a Join. A join is a relation (and there are more types) between tables. In your case you will do
select *
from employer emp inner join job jjj on emp.id = jjj.employer _id
The ids are usefull, code-wise, when you have to update/delete a record. In this case usually you know everything about your record, id included, then you will use the id (also because ids usually have indexes, so the queries are faster). You can usually create indexes in the columns you use in filters, in order to reduce the execution time of your queries.
We need to distinguish between business (or candidate) keys and technical (or surrogate) keys. The business key is the data item(s) which uniquely identify this row in the real world. The technical key is a convenience for data management, generated by some computer process such as a sequence or sys_guid().
Yes, the use of technical keys means storing redundant information but this is a case where practicality trumps theory. Primary keys should not change but in real life they can (e.g. people change their name due to various life events). Technical keys have no meaning so do not change. Business keys are often compound keys, which is often inconvenient for enforcing foreign keys (and occasionally highly undesirable, for instance when the business key is a sensitive data item such as Social Security Number).
So, it is common for tables to have an ID column as the primary key, which is used for foreign key relationships, and a unique constraint to enforce the business key.
In your first example username is a business key and id is a technical key. This is one reason why we should have two data models. The Logical Data Model has an Entity called user with a candidate key of username. The physical data model has a Table called user with a primary key of id and a unique key of username.
For your second example, it seems you're modelling a Situations Vacant job board. The relationship between Employer and Job is one to many, that is an employer can advertise many jobs. So the Job table has its own primary key, id, plus a foreign key employer_id which references the primary key of the Employer table. This means we can find all the jobs for a specific employer. But because the job table has its own primary key we can identify each job so that we can distinguish the Janitor job at Harrisons Pharmaceuticals from the Janitor job at Ravi's Cash'n'Carry. (Which incidentally shows why we need technical keys: imagine if the employer_id foreign key was a string of varchar2(128) for each row on the Job table. )
In a Logical Data Model the employer_id would be implied on the Entity job by a link to the Entity employee but would be shown (actually it might, it depends on the tool). In the physical model the column must be added to the dependent table, because database constraints (and joins!) physically need the column in order to work.
So we can see that Normalisation applies to the representation and storage of business data but the practicalities of database engines mean that we need additional columns to manage the data.

If I got many to many relationship data first, how do I insert them to my table?

Say I have a customer table, a product table and an order table to record who buys what, the order table basically has 2 foreign keys, customer_id & product_id.
Now I got the order information first, within in it I can't find the customer information in my local database. As it turns out this is a new customer, whose information will come later from another thread/queue. To make things even worse the customer id I got from the order information is not the same one I used locally. My local customer id is INTEGER PRIMARY KEY (I do record that "true customer id" as another column and set index on it)
So how I do record this order information? I can come up with some clumsy solution, e.g. if I can't find contact info, I insert a record for it first. Later after I get the real information for this customer, I update customer & order table. But I was wondering is there any "standard" way for the situation like this?
Inserting NULL values, and then updating with the real values later, is simple and will work (if you don't have a NOT NULL constraint).
You should use a transaction so that concurrent users don't see the incomplete data.
You could use deferred foreign key constraints:
If a statement modifies the contents of the database such that a deferred foreign key constraint is violated, the violation is not reported immediately. Deferred foreign key constraints are not checked until the transaction tries to COMMIT. For as long as the user has an open transaction, the database is allowed to exist in a state that violates any number of deferred foreign key constraints.
However, deferred foreign key constraints are useful only if you are inserting values that violate the constraint; a NULL value is not considered a FK violation.

Creating database tables regarding Primary and Foreign Keys

I'm doing an activity online where I need to create an example database for an Airline. It details the general information needed to be put into each table but I need help linking certain tables.
I've drawn up tables in Word to help me grasp the connections between tables but I'm unsure if I'm doing it correctly.
I have a table called 'Staff' that looks like this:
I was asked to create another table that provides each staff members previous work experience such as the company they worked for and join and end dates, etc.
The 'Work Experience' table:
My question is, what would be the primary key for the Work Experience table? Seeing as Staff_ID references back to the Staff table could it be both a Primary Key and a Foreign Key?
Just create a generic work_experience_id or we_id(whatever you way you want it) so that every time you want to call previous work experience for staff you just select generic id primary key.