如何链接表mysql

时间:2013-06-01 09:18:09

标签: mysql sql select

我的mysql数据库中有3个表:student, progress and subject。当我尝试选择数据时:

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

我得到下表:

id  mark  pname
1   5     Math
1   5     Physics

表格进度我只有一个条目:

id  mark   id_student   id_subject
1   5      1            1

如何通过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)
);

2 个答案:

答案 0 :(得分:1)

SELECT progress.id, progress.mark, subject.pname 
FROM progress LEFT OUTER JOIN subject ON (progress.id_subject= subject.id)
WHERE   progress.id_student = 1;

答案 1 :(得分:1)

尝试

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