一個子查詢返回值多於一個的錯誤

創建一個學生,教師,以及記錄多對多關係的學生教師關係表:

create table teacher
(
id varchar(40) primary key,
name varchar(20)
);

create table student
(
id varchar(40) primary key,
name varchar(20)
);
create table teacher_student
(
t_id varchar(40),
s_id varchar(40),
primary key(t_id,s_id),
constraint t_id_FK foreign key (t_id) references teacher(id),
constraint s_id_FK foreign key (s_id) references student(id)
);

在查找教師實體時遇到一個錯誤,查方法的源碼是:

public Teacher find_t(String id) throws SQLException{
QueryRunner qr = new QueryRunner(JdbcUtils_C3P0.getDs());
String sql = "select * from teacher where id=?";
Teacher t =  (Teacher) qr.query(sql, id, new BeanHandler(Teacher.class));

//根據外鍵關係表,取出學生的信息
//這個sql語句是錯誤的額,子查詢返回的值多餘一個,
sql = "select * from student where id=(select s_id from teacher_student where t_id=?)";
List<Student> list = (List<Student>) qr.query(sql, t.getId(), new BeanListHandler(Student.class));
t.getSet().addAll(list);

return t;
}

運行結果報錯爲:

java.sql.SQLException: Subquery returns more than 1 row Query: select * from student where id=(select s_id from teacher_student where t_id=?) Parameters: [1]

因爲教師可以對應着多個學生,所以子查詢返回的值自然可以多於一個,而當子查詢跟隨在=、~=、<、<=、>、>=之後或子查詢用作表達式時,這種情況是不允許的。

所以sql語句應該使用連接查詢:sql="select * from student s,teacher_student t_s where s.id=t_s.s_id and t_s.t_id=?";

發佈了36 篇原創文章 · 獲贊 18 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章