简体   繁体   中英

How to link the tables mysql

I have 3 tables in my mysql database: student, progress and subject . When I try to select data:

SELECT progress.id, progress.mark, subject.pname FROM progress, subject WHERE   progress.id_student = 1;

I get the following table:

id  mark  pname
1   5     Math
1   5     Physics

Table progress I only have one entry:

id  mark   id_student   id_subject
1   5      1            1

How can I get student progress by student_id ?

CREATE DATABASE students;
USE students;
CREATE TABLE student (
id int NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
address varchar(60) NOT NULL,
byear int NOT NULL,
eyear int NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE subject (
id int NOT NULL AUTO_INCREMENT,
pname varchar(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE progress (
id int NOT NULL AUTO_INCREMENT,
mark int NOT NULL,
id_student int NOT NULL,
id_subject int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES student (id),
FOREIGN KEY (id) REFERENCES subject (id)
);
SELECT progress.id, progress.mark, subject.pname 
FROM progress LEFT OUTER JOIN subject ON (progress.id_subject= subject.id)
WHERE   progress.id_student = 1;

Try

SELECT progress.id, progress.mark, subject.pname 
FROM progress, subject
WHERE progress.id_student = 1 AND progress.id_subject = subject.id;

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.

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