关于外键关联
CREATE TABLE student( id INT AUTO_INCREMENT PRIMARY KEY, reg_no INT NOT NULL, `name` VARCHAR(20) NOT NULL, sex VARCHAR(20) NOT NULL, age INT NOT NULL, grade VARCHAR(20) NOT NULL, major VARCHAR(50) NOT NULL ); INSERT INTO student VALUES(NULL,20171201,"梅长苏","男",31,"2008","哲学系"); INSERT INTO student VALUES(NULL,20171202,"萧景琰","男",30,"2008","政治系"), (NULL,20171203,"飞流","男",18,"2016","人体学"), (NULL,20171204,"萧景恒","男",35,"2006","政治系"), (NULL,20171205,"宫羽","女",25,"2013","声乐系"), (NULL,20171206,"霓凰","女",31,"2008","国际关系系"), (NULL,20171207,"秦般弱","女",30,"2009","同学专业");
CREATE TABLE course( id INT AUTO_INCREMENT PRIMARY KEY, courseid VARCHAR(20) NOT NULL, major_name VARCHAR(20) NOT NULL, coursename VARCHAR(20) NOT NULL, courtime DATETIME NOT NULL, courteacher VARCHAR(20) NOT NULL )CHARSET "UTF8"; INSERT INTO course(courseid,major_name,courname,courtime,courteacher) VALUES("C1011","哲学系","哲学概论","10:00:00","黄玉生"), ("C1012","哲学系","科学技术哲学","10:00:00","梧桐"), ("C1013","哲学系","伦理学","10:00:00","王俊人"), ("C1013","哲学系","美学","10:00:00","小英")
ALTER TABLE course ADD FOREIGN KEY (major_name) REFERENCES student(major);
老师你好,上述代码的主键设置报错了.原因是主表student的major字段不是主键吗?
course和student的外键关联具体代码应该怎么写?
0
收起
正在回答
3回答
同学你好,这里的column要设为student的id,表示根据student表的主键id来查找地址。
在collection标签中添加select="getCourse",调用getCourse方法。
如下图所示:
关于外键的设置,可以参考如下:
例如:一个人对应一个地址,此时,可以将“人”设为子表person,“省市”设为父表address。
在子表中增加一个字段addrid,关联“省市”的主键id,这个addrid就是表person的外键。
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~
程咬金的三板斧
2019-05-15 22:04:55
需要在数据库进行的操作:
SELECT * FROM course WHERE major_name="哲学系"
映射配置文件该部分代码:
<select id="findStudents" resultMap="forStudents"> select * from student <if test="id != null"> where id = #{id} </if> </select> <resultMap id="forStudents" type="com.imooc.entity.Students"> <id column="id" property="id"></id> <collection property="courses" column="major" ofType="com.imooc.entity.Course" ></collection> </resultMap> <select id="getCourse" resultType="com.imooc.entity.Course"> select * from course where major_name = #{major} </select>
吃吃吃鱼的猫
2019-05-15 18:27:40
同学你好,首先,插入语句字段“courname”写错了,应该为“coursename”。
当设置外键时,一般情况下,我们会为student的表设置外键。
1.先添加courseid字段,关联course表。
alter table student add courseid int(20);
2.为student表添加外键。当关联course表时,必须关联course表的主键。
alter table student add CONSTRAINT fk_student FOREIGN KEY (courseid) REFERENCES course(id)
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~
3. Java 数据库开发与实战应用
- 参与学习 人
- 提交作业 357 份
- 解答问题 8016 个
本阶段将带你学习MySQL数据库,JDBC接口,MyBatis框架等,带你掌握的数据的存放和管理。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星