简体   繁体   English

两个表之间的关系应该是什么,以便每个学生可以有单独的markid

[英]what should be the relation ship between both the tables so each student can have separate marksid

i am new to sql I have 2 tables first one with marks and second one with students. 我是sql的新手,我有2个表,第一个带有标记,第二个带有学生。 marks have a primary key of marksid and students have primary key student id. 标记具有marksid的主键,学生具有主键student ID。 I want to know what should be the relation ship between both the tables so each student can have separate marksid. 我想知道两个表之间的关系应该是什么,以便每个学生可以有单独的markid。 and what will be the sql query to get their data. 以及将要获取其数据的sql查询是什么。

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. 我已尝试使用此选择查询s =“ select s。学生名,z.Hourly1Marks from Student s,marks z”一对一关系,但它显示的是笛卡尔乘积。

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). 研究INNER JOIN(如果每个学生都有一个分数,即1:1关系)和LEFT JOIN(如果每个学生可以有多个分数,即1:n关系)的概念。

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 对于1:1关系的情况,或

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. 对于1:N关系的情况。

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. 并且Studend和Marks之间的关系是“一个学生可以拥有0个或更多个Marks”,那么您需要在Marks表中添加一列-称为studentID ,此列用作Student表的外键。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM