i am new to sql I have 2 tables first one with marks and second one with students. marks have a primary key of marksid and students have primary key student id. I want to know what should be the relation ship between both the tables so each student can have separate marksid. and what will be the sql query to get their data.
I have tried one to one relationship with this select query s="select s.Student Name,z.Hourly1Marks from Student s,marks z " but it is showing Cartesian product of entries.
Study the concept of INNER JOIN (if each student has one mark, ie 1:1 relationship), and LEFT JOIN (if each student can have multiple marks, ie 1:n relationship).
You used an inner join without a restriction. What you need is something like
SELECT S.name, Z.marks
FROM students S
JOIN marks Z ON S.student_id = Z.student_id
or equivalently
SELECT S.name, Z.marks
FROM students S, marks Z
WHERE S.student_id = Z.student_id
for a 1:1 relationship case, or
SELECT S.name, Z.marks
FROM students S
LEFT JOIN marks Z ON S.student_id = Z.student_id
for a 1:N relationship case.
Supposing you have two tables:
Students
--------------
IDStudent
Name
....
Marks
--------------
IDMarks
Hourly1Marks
and the relation between Studend and Marks is 'A student could have 0 or more Marks' then you need to add a column in the table Marks - call it studentID
and this column is used as foreign key for the student table.
then you can write this query
select s.Name, z.Hourly1Marks
from Student s left join marks z
on z.studentID = s.IDStudent
that will give you back all students and their marks (also the student without any marks) or, if you want only the students with at least one mark
select s.Name, z.Hourly1Marks
from Student s inner join marks z
on z.studentID = s.IDStudent
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.