有两张表 分别是学生表和教师表,学生表主键是学号,教师表主键为教职工号,如何通过客户端传递的参数(学号或者教职工号)来进行同时查询两张表,并返回正确数据,相关的mysql语句怎么写
同时查询的关键在于两个表如何关联,假定学生表的字段为学号、教职工号、姓名,教师表的字段为教职工号、姓名,条件为学号或教职工号,并且你没有使用持久层框架,那么示例代码如下。
public class Test {
public static void main(String[] args) {
// 条件
String studentNo = "";
String teacherNo = "";
// 最终结果
String sql = "select * from 学生表 left join 教师表 on 学生表.教职工号 = 教师表.教职工号";
String where = null;
if (studentNo != null && studentNo.length() > 0) {
where = "学生表.学号 = '" + studentNo + "'";
}
if (teacherNo != null && teacherNo.length() > 0) {
if (where == null) {
where = "教师表.教职工号 = '" + teacherNo + "'";
} else {
where = where + " and " + ("教师表.教职工号 = '" + teacherNo + "'");
}
}
if (where != null) {
sql = sql + " where " + where;
}
}
}