I am creating a database which is similar to the following situation.
Table1:
CustomerType1 (Column: CustomerId,...)
Table2:
CustomerType2 (Column: CustomerId,...)
Table 3:
Orders (Columns: OrderId, CustomerId...)
Now, how can I relate the customerId of orders table to customerId column of CustomerType1 and CustomerType2 tables?
(I am working on a windows phone app, so if you can help me with the attributes used in creating a database similar to above situation than it would be helpful)
Thanks
Your database should be composed of 4 tables:
- Customer(CustomerId, common stuff to all customers)
- CustomerType1(CustomerId, specific stuff to type 1 customers)
- CustomerType2(CustomerId, specific stuff to type 2 customers)
- Orders(OrderId, CustomerId, other order stuff)
The table columns CustomerType1.CustomerId and CustomerType2.CustomerId provide a reference to the Customer table by means of the Customer.CustomerId column. Also a reference to the Orders table and Customer table can be achieved by using the Orders.CustomerId and Customer.CustomerId columns.
For clarity, the tables CustomerType1, CustomerType2 and Orders would all have a Foreign key constraint as following:
FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
Related
I have two tables, table1 has a foreign key of table2. I want to get some info from table1 including a column which both table1 and table2 have. Should I join these two table to get the info?
For example:
I have two tables Course and Student, such as below
enter image description here
Solution1:
Course
|project CourseId, CouseName, StudentName, StudentId
Solution2:
Course
| project CourseId, CourseName, StudentName
| join Student
on $left.StudentId == $right.StudentId
| project CourseId, CourseName, StudentName
To get the CourseId, CourseName and StudentName, which solution is correct? Is it a good practice to pick solution2?
Please ignore the table design. It is just an example. The issue is coming from a real project that we need a query from one table which contains a foreign id and common column from other table. The query should give the common column back. Is it necessary that join the second table to get the common column?
Course table should not have Student name, it’s redundant data. And yes you can use inner join or left join on student id. Just bear in mind with the given information provided by you, the case where student id can be or cannot be null in course table.
I believe the concept of join should only be used when we need data from 2 or more tables. If you have all the required data in a single table, why you need a join. If were you, I will surely move forward with first solution. Thanks
Your tables do not follow those three normalization forms.
This is how entities and relationships should be organized if we are talking about the common scenario of designing a database for a school or something something similar to this.
There is a Many to Many relationship between Courses and Students, which allows us to associate N students with one course, and M courses with one student (one course can be attended by many students, and one student can attend many courses).
Also, this design follows the 3rd Normalization Form.
Learn more about normalization forms
Learn more about Many to Many relationships
I have student table in SQL Server.
In my web application I have textBox, where I can input a date (dd-mm-yyyy). This date means that any(application know which exactly) student was absent this day.
How to save this date in SQL Server?
There is no problem when student is absent just one day per all life, because I can create one additional column in my student table and save there date of absent.
But I don't know how many days student will absent. I can add thousand columns to my student table and write in there dates of absents, but it's very bad solution.
So, how to save dates of absence in SQL?
I wrote my web application in ASP.NET, C#, SQL Server.
You need to have another table to keep track of the dates the student was absent.
Say your current table is as follows:
Student
-------
StudentId [PK]
...
So you would now create another table as:
StudentAbsent
-------
StudentAbsentId [PK]
StudentId [FK, Student.StudentId]
AbsentDate
To get the dates the student with id=5 was absent you'd do something like the following in SQL
SELECT AbsentDate FROM StudentAbsent
WHERE StudentId = 5
Oh and BTW you'd want to read more on relationships. If it's a 1-1 relationship one row of table1 is related to one row of table2.
If it's a 1-n relationship, one row of table1 is related to many rows of table2 (as is the case above)
If it's a n-n relationship, one row of table1 is related to many rows of table2 and vice-versa.
You have to create another table called absents with three columns:
id (primary index and auto_increment)
student_id (should not be unique)
date
The id column is just the id of the absent (it's a good practice to have id for every row on a table). The student_id is a reference to id column of students table, identifying the correct student. And the date column is the date of absent.
Another good practice is to create relationship internally and set triggers to actions like delete (what should you do if the student is deleted?).
I have two tables
contact table
contactID (PK auto increment)
FirstName
LastName
Address
etc..
Patient table
PatientID
contactID (FK)
How can I add the contact info for Patient first, then link that contactID to Patient table
when the contactID is autoincrement (therefore not known until after the row is created)
I also have other tables
-Doctor, nurse etc
that also links to contact table..
Teacher table
TeacherID
contactID (FK)
So therefore all the contact details are located in one table.
Is this a good database design?
or is it better to put contact info for each entity in it's own table..
So like this..
Patient table
PatientID (PK auto increment)
FirstName
LastName
Address
Doctor table
DoctorID (PK auto increment)
FirstName
LastName
Address
In terms of programming, it is easier to just have one insert statement.
eg.
INSERT INTO Patient VALUES(Id, #Firstname,#lastname, #Address)
But I do like the contact table separated (since it normalize the data) but then it has issue with not knowing what the contactID is until after it is inserted, and also probably needing to do two insert statements (which I am not sure how to do)
=======
Reply to EDIT 4
With the login table, would you still have a userid(int PK) column?
E.g
Login table
UserId (int PK), Username, Password..
Username should be unique
You must first create the Contact and then once you know its primary key then create the Patient and reference the contact with the PK you now know. Or if the FK in the Patient table is nullable you can create the Patient first with NULL as the ContactId, create the contact and then update the Patient but I wouldn't do it like this.
The idea of foreign key constraints is that the row being referenced MUST exist therefore the row being referenced must exist BEFORE the row referencing it.
If you really need to be able to have the same Contact for multiple Patients then I think it's good db design. If the relationship is actually one-to-one, then you don't need to separate them into two tables. Given your examples, it might be that what you need is a Person table where you can put all the common properties of Doctors, Teachers and Patients.
EDIT:
I think it's inheritance what you are really after. There are few styles of implementing inheritance in relational db but here's one example.
Person database design
PersonId in Nurse and Doctor are foreign keys referencing Person table but they are also the primary keys of those tables.
To insert a Nurse-row, you could do like this (SQL Server):
INSERT INTO Person(FirstName) VALUES('Test nurse')
GO
INSERT INTO Nurse(PersonId, IsRegistered) VALUES(SCOPE_IDENTITY(), 1)
GO
EDIT2:
Google reveals that SCOPE_IDENTITY() equivalent in mysql is LAST_INSERT_ID() [mysql doc]
EDIT3:
I wouldn't separate doctors and nurses into their own tables so that columns are duplicated. Doing a select without inner joins would probably be more efficient but performance shouldn't be the only criteria especially if the performance difference isn't that notable. There will many occasions when you just need the common person data so you don't always have to do the joins anyway. Having each person in the same table gives the possibility to look for a person in a single table. Having common properties in a single table also allows you have to have doctor who is also a patient without duplicating any data. Later, if you want to have more common attributes, you'd need to add them to each "derived" table too and I will assure you that one day you or someone else forgets to add the properties in one of the tables.
If for some reason you are still worried about performance and are willing to sacrifice normalization to gain performance, another possibility is to have all person columns in the same table and maybe have a type column there to distinguish them and just have a lot of null columns, so that all the nurse columns are null for doctors and so on. You can read about inheritance implementation strategies to get an idea of even though you aren't using Entity Framework.
EDIT4:
Even if you don't have any nurse-specific columns at the moment, I would still create a table for them if it's even slightly possible that there will be in the future. Doing an inner join is a pretty good way to find the nurses or you could do it in the WHERE-clause (there a probably a billion ways to do this). You could have type column in the Person table but that would prevent the same person being a doctor and a patient at the same time. Also in my opinion separate tables is more "strict" and more clear for (future) developers.
I would probably make PersonId nullable in the User table since you might have users that are not actual people in the organization. For example administrators or similar service users. Think about in terms of real world entities (forget about foreign keys and nullables), is every user absolutely part of the organization? But all this is up to you and the requirements of the software. Database design should begin with an entity relationship design where you figure out the real world relationships without considering how they will be mapped to a relational database. This helps you to figure out what the actual requirements are.
I have an audit trailing system in my project from http://doddleaudit.codeplex.com/.
As you can see on this image it records the EntityTable - which is the table name, and the EntityTableKey - which is the primary key
I would like to associate the audit records with the tables it had recorder, then query the result in linq to sql. But the problem is if the audit table has record for orders and record for products it will never know just by the primary key, where does the record belong, thus i need to use the table name as part of the key.
So the question is: Is it possible to create a relation that will have a composite primary key that contains the table name in it?
AuditRecord to Orders
AuditRecord to Products
You could do it, but I would recommend a bit different approach.
Don't use char/varchars/nvarchar in your PK/FK, it bloats the index. I would rather create another table that will hold TableId/TableName pairs of all your tables (you can use sys.tables.object_id for your id if you wish) and have a FK in AuditRecords to it. Then establish composite key between AuditRecords and AuditRecordFields (Id, TableId).
Another thing:
EntityTable and AssociationTable should be of sysname type
AuditDate can be of type Date (available from SQL Server 2008)
EDIT:
If you like to access audit records from each object, you can create a base class for your audited objects and implement following method (beware, it's untested):
public IQueryable<AuditRecord> AuditRecords
{
get
{
MyContext ctx = new MyContext();
var ars = from ar in ctx.AuditRecords
where ar.EntityTable.Equals(this.GetType().Name)
select ar;
return ars;
}
}
I have to create an attendance management system of our college..
.the Requirements are..
there are 6 subjects
every subject has a table for every month..
every class conducted is recorded and is numbered from 1 to n..and the present candidates are given the count if present...
at the end of every month, total classes taken by all 6 subjects are summed up...and total classes attended by each student is summed up and a percentage is calculated...(total present classes)/(total classes )*100...
there are 120 students...
please help me create an efficient way to create the databases...
note....
the application should allow you to view through all the absent classes he did not attend for reference..(so every absent class must be recorded)
My..attempts:
one way i tried was:
create tables for each subject...then
6 tables required
cons:
*every day must be a column and the copy of 6 tables should be created every month.
i.e 6 sub*12 months =72 tables every year
also a extra classes can be taken per subject...so if a subject is taken twice on the day,3 cases arrive--> present for both,absent for both,present for only one..*
2..the second method I've tried is:
create a table for each student with the same db schema ..(with subjects as columns )
con:
12 students will require 120 tables
:P
Any bright ideas guys...would really help if you give me ideas how to construct a db schema for this kinda application.......
thankyou.....
Students table:
StudentID int identity PK
LastName string(20)
FirstName string(20)
Classes Table:
ClassID int identity PK
ClassName string(50)
SubjectID int FK to Subjects table (not shown)
TermID int FK to Terms table (not shown)
Students to Classes table:
STCID int identity PK
ClassID int FK to Classes table
StudentID int FK to Students table
Attendance Table:
AttendID int identity PK
STCID int FK to Student To Class table
Date date/time
PK means Primary Key. FK means Foreign Key (it associates to the Primary Key in other tables).
The Students to Subjects table connects the students with their subjects. For each subject that a student is assigned, add a record to the Students to Subjects table. For each date that a student attends a particular subject, add a single record to the Attendance table.
First of all, you definitely do not need to duplicate tables for each month or student. That's madenss.
You can calculate the month from the date, so just storing a date solves that.
Here's my initial reaction.
You need tables for students, subjects, registrations, classes and attendence.
Registrations table:
ID
Student_ID
Subject_ID
Classes table (use a different name) shows all of the valid class dates (required to calculate attendance %):
ID
Subject_ID
Class_Date
Attendance table:
ID
Student_ID
Class_ID (refers to the ID field in the class table)
(modify the names to suit your conventions)
This way attendance contains a record of every appearance by every student in every class. You can determine which classes each student missed in each subject by SQL queries.
All of the logic you described can be handled with this structure unless I missed something. Keep your data model clean and let your code do the work.
Here's some SQL DDL based on #nycdan's answer but using natural keys rather than artificial (surrogate?) keys because doing so allows for improved referential integrity i.e. Attendance can and should reference Enrollment to ensure attendance cannot be logged for a student who is not registered on that course. I've also changed a few names. I'm only including the most salient attributes. :
CREATE TABLE Students (student_ID INTEGER NOT NULL UNIQUE);
CREATE TABLE Courses (course_ID CHAR(6) NOT NULL UNIQUE);
CREATE TABLE Enrollment
(
course_ID CHAR(6) NOT NULL
REFERENCES Courses (course_ID),
student_ID INTEGER NOT NULL
REFERENCES Students (student_ID),
UNIQUE (course_ID, student_ID)
);
CREATE TABLE CourseSchedules
(
course_ID CHAR(6) NOT NULL
REFERENCES Courses (course_ID),
class_date DATE NOT NULL,
UNIQUE (course_ID, class_date)
);
CREATE TABLE Attendance
(
student_ID INTEGER NOT NULL,
course_ID CHAR(6) NOT NULL,
class_date DATE NOT NULL,
FOREIGN KEY (course_ID, student_ID)
REFERENCES Enrollment (course_ID, student_ID),
FOREIGN KEY (course_ID, class_date)
REFERENCES CourseSchedules (course_ID, class_date),
UNIQUE (course_ID, class_date, student_ID)
);