三表关联查询
Posted qq_48838980
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了三表关联查询相关的知识,希望对你有一定的参考价值。
目录
一、创建三张表:学生表、选课表、课程表
- 在自定义的数据库中创建三个表
1、学生表(学号, 姓名, 性别, 年龄, 电话) - 学号是字符串类型
- 运行SQL语句创建学生表
CREATE TABLE student (
s_id int(11) NOT NULL AUTO_INCREMENT,
s_number int(11) NOT NULL,
s_name varchar(30) DEFAULT NULL,
s_gender varchar(10) DEFAULT NULL,
s_age int(11) DEFAULT NULL,
s_phone VARCHAR(11) DEFAULT NULL,
PRIMARY KEY (`s_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
- 运行SQL语句给student学生表插入记录
INSERT INTO student VALUES ('1','19205111', '张三', '女',18,'1234569290');
INSERT INTO student VALUES ('2','19205112', '李四', '女',20,'1234785890');
INSERT INTO student VALUES ('3','19205113', '王五', '女',19,'1238737890');
INSERT INTO student VALUES ('4','19205114', '刘艳', '女',10,'1234593690');
2、选课表(学号, 课程号, 成绩)
- 运行SQL语句创建学生表
CREATE TABLE selecourse (
sc_id int(11) NOT NULL AUTO_INCREMENT,
sc_number int(11) NOT NULL,
sc_classnumber int(20) NOT NULL,
sc_score int(10) NOT NULL,
PRIMARY KEY (`sc_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
- 运行SQL语句给student学生表插入记录
INSERT INTO selecourse VALUES ('1','19205111', '123', '90');
INSERT INTO student VALUES ('2','19205112','234', '89');
INSERT INTO student VALUES ('3','19205113','345', '99');
INSERT INTO student VALUES ('4','19205114','456', '78');
3、课程表(课程号, 课程名, 课时数) - 课程号是字符串类型
- 运行SQL语句创建学生表
CREATE TABLE timetable (
t_id int(11) NOT NULL AUTO_INCREMENT,
t_classnumber int(20) NOT NULL,
t_name VARCHAR(30) NOT NULL,
t_classhours int(10) NOT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
- 运行SQL语句给student学生表插入记录
INSERT INTO timetable VALUES ('1', '123', '心理健康教育','10');
INSERT INTO student VALUES ('2','234', 'java','30');
INSERT INTO student VALUES ('3','345', 'python','25');
INSERT INTO student VALUES ('4','456', '前端技术','25');
二、查询任务
1、在映射器配置文件里引入结果映射元素
2、添加按姓名查询用户记录功能,更新,查找,删除
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.tp.mybatis.mapper.UserMapper">
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="address" property="address"/>
</resultMap>
<select id="findById" parameterType="int" resultType="User">
SELECT * FROM t_user WHERE id = #{id};
</select>
<select id="findAll" resultType="User">
SELECT * FROM t_user;
</select>
<select id="findByName" parameterType="string" resultType="User">
SELECT *FROM t_user where name like concat (#{name},"%");
</select>
<insert id="insert" parameterType="User"
useGeneratedKeys="true" keyProperty="id">
insert into t_user(name ,age,address)
value (#{name},#{age},#{address});
</insert>
<update id="update" parameterType="User">
UPDATE t_user SET name =#{name}, age=#{age},
address =#{address} where id=#{id};
</update>
<delete id="deleteById" parameterType="int">
DELETE FROM t_user WHERE id=#{id};
</delete>
</mapper>
3、在UserMapper接口里增加插入、更新、删除方法
package net.tp.mybatis.mapper;
import net.tp.mybatis.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 功能:用户映射器接口
* 作者:tp
* 日期:2021年03月04日
*/
public interface UserMapper {
// @Select("SELECT * FROM t_user;")
List<User> findAll();
//@Select(" SELECT * FROM t_user WHERE id = #{id}")
User findById(int id);
List<User> findByName(String name);
int insert (User user);
int update(User user);
int deleteById(int id);
}
4、在测试类TestUserMapper里添加测试方法
package net.zjs.mybatis.mapper;
import net.tp.mybatis.bean.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
/**
* 功能:测试用户映射器接口
* 作者:zjs
* 日期:2021年03月04日
*/
public class TestUserMapper {
private SqlSession sqlSession; // SQL会话
private UserMapper userMapper; // 用户映射器
@Before
public void init() {
try {
// 读取MyBatis配置文件作为字符输入流
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 基于MyBatis配置文件构建SQL会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 利用SQL会话工厂获取SQL会话
sqlSession = factory.openSession();
// 利用SQL会话获取用户映射器对象
userMapper = sqlSession.getMapper(UserMapper.class);
// 提示用户SQL会话对象创建成功
System.out.println("sqlSession对象已创建。");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindById() {
int id = 1;
User user = userMapper.findById(id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到。");
}
}
@Test
public void testFindAll() {
List<User> users = userMapper.findAll();
users.forEach(user -> System.out.println(user));
}
@Test
public void testFindName(){
String name= "王";
List<User> users =userMapper.findByName(name);
if (users.size() >0){
users.forEach(user -> System.out.println(user));
}else {
System.out.println("没有找到姓名为:["+name+"]的记录!");
}
}
@Test
public void testInsert(){
User user =new User();
user.setName("王雨涵");
user.setAge(30);
user.setAddress("龙马潭区长桥路2号宿舍");
int count =userMapper.insert(user);
sqlSession.commit();//提交数据库操作
if(count>0){
System.out.println("记录插入成功!");
System.out.println("插入的新记录:"+user);
}else {
System.out.println("插入失败!");
}
}
@Test
public void testUpdate(){
User user=userMapper.findById(4);
System.out.println("更新前的记录:"+user);
user.setName("萌萌");
user.setAge(18);
user.setAddress("北京市朝阳区北苑路6号楼");
int count =userMapper.update(user);
sqlSession.commit();//提交数据库操作
if(count>0){
System.out.println("记录更新成功!");
System.out.println("更新后的记录:"+user);
}else {
System.out.println("更新失败!");
}
}
@Test
public void testDeleteById(){
int id = 4;
User user =userMapper.findById(id);
System.out.println("待删除的记录:"+user);
userMapper.deleteById(id);
sqlSession.commit();//提交数据库操作
System.out.println("编号为["+id+"]的记录删除成功!");
user=userMapper.findById(id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到。");
}
}
@After
public void destroy() {
// 关闭SQL会话
sqlSession.close();
// 提示用户SQL会话对象关闭
System.out.println("sqlSession对象已关闭。");
}
}
以上是关于三表关联查询的主要内容,如果未能解决你的问题,请参考以下文章