3

I have two tables, say teacher and student. I want to build a third table called class.

The class table will have one column for the teacher of the class, but I want to see if their is an elegant way to represent the students. My first thought is to have say 30 columns.. student1, student2 and have quids for each of these that tie back to a row in the student table.

But I am asking to see if there is a more preferred solution. The above solution seems clunky.

4
  • Are you asking about how to store the students that are in each class, or how to select them such that you will see a column for each student in the class? The structure of your tables does not necessarily have to correspond to how you would like your query results to look. Commented Sep 21, 2010 at 18:06
  • 1
    if you ever have a SQL table design where you have columns of the same name except an attached incrementing number (like your student1, student2...), you have a bad design! this is why they invented the phrase "just say no" Commented Sep 21, 2010 at 18:43
  • 1
    +1 for detecting the "database smell" of multiple columns when they should be rows. Commented Sep 21, 2010 at 19:15
  • @KM, yeah I knew it was bad was trying to think of a couple different ways to do it right. Commented Sep 23, 2010 at 18:34

4 Answers 4

4

If it was me I would have a 4th table called attendees or similar which links the students to the class as it's a many to many relationship. Which would contain the Class ID and the Student ID as a minimum..

Sign up to request clarification or add additional context in comments.

3 Comments

+1 ... by all means yes ... I would do the same for teachers because is there only 1 and only 1 teacher for each class? e.g. ClassDetail(ClassID, PersonID, Role)
Selected this answer as it is the most straight forward. I need to look at the PIVOT solution but this solution works for now.
@Maestro1024 Take a look at my StudentClass table, it's exactly that.
3

The class "table" is not a table but a result of running a stored procedure with pivoting of data.

And data structure is as follows:

Student: Id, ...
Teacher: Id, ...
StudentClass: StudentId, ClassId, ...
Class: Id, TeacherId, ...

Comments

3

SQL Server has this thing called sparse columns However I would advice against it. Normalize your data and then PIVOT/crosstab the results when you want to display it side by side

Comments

2

It's very clunky.

Have three tables:

  1. Teacher
  2. Student
  3. TeacherStudent, which is a many-many table to join the two.

Do the pivot method expressed in the other answer. It makes more sense.

1 Comment

Thanks for the upvotes, but I think he's after the PIVOT keyword.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.