SQL Noob。 “外键约束不正确”

时间:2017-02-17 17:14:38

标签: mysql sql foreign-keys

我已经在这篇文章中查看了其他主题,并试图让我的脚本适应它们,但无济于事。所以我在这里发帖。

我有两张桌子,科目和学生。在这些内容中,有两个主键(subject_id和student_id),请参考full view of the two tables的图像(在phpmyadmin中完成)。

我的目标是创建第三个表,其中包含entry_id(主键),subject_id(FK),subject_name(FK),subjectexamboard(FK),student_id(FK)和studentfirstname(FK)。

以下是我试图在phpmyadmin上运行的代码:

   ...statements for the line plot up to here...
   ax_skal = plt.axes([0.25, 0.05, 0.65, 0.02], facecolor="lightgrey")
   sl_xticks = np.arange(0.6,2, 0.2)
   ax_skal.set_xticks(sl_xticks)    
   s_skal = Slider(ax_skal, 'time scale', 0.5, 2, valinit=1, valfmt='%0.1f')
   s_skal.vline.set_color('blue')

感谢您的帮助,请放轻松,因为我对SQL很新。

5 个答案:

答案 0 :(得分:0)

检查每个列对的FK约束,它们应该是相同的数据类型

答案 1 :(得分:0)

你想做什么。您需要查询或视图。

您在上面尝试做的事情会破坏任何类型的database normalization

您的输入表如下所示:

CREATE TABLE entries3 (
  entry_id INT NOT NULL AUTO_INCREMENT,
  subject_id INT NOT NULL,
  student_id INT UNSIGNED NOT NULL,
  PRIMARY KEY (entry_id),
  CONSTRAINT fk_entry_subjects FOREIGN KEY (subject_id) REFERENCES subjects(subject_id),
  CONSTRAINT fk_entry_students FOREIGN KEY (student_id) REFERENCES students(student_id)
);

然后用

查询它
select sub.*, stu.*
from entries3 as ent
  inner join subjects as sub 
    on ent.subject_id = sub.subject_id
  inner join students as stu 
    on ent.student_id = stu.student_id

答案 2 :(得分:0)

应该是CONSTRAINT name_of_constrainT FOREIGN KEY

假设您的名字有效

   CREATE TABLE entries3(
  entry_id INT NOT NULL AUTO_INCREMENT,
  subject_id INT NOT NULL,
  subject_name VARCHAR(20) NOT NULL,
  subjectExamBoard VARCHAR(10) NOT NULL,
  student_id INT UNSIGNED NOT NULL,
  studentFirstName VARCHAR(20) NOT NULL,
  studentLastName VARCHAR(40) NOT NULL,
  PRIMARY KEY (entry_id),
  CONSTRAINT subject_id_fk      FOREIGN KEY  (subject_id)       REFERENCES subjects(subject_id),
  CONSTRAINT subject_name_fk    FOREIGN KEY  (subject_name)     REFERENCES subjects(subject_name),
  CONSTRAINT subjectExamBoar_fk FOREIGN KEY  (subjectExamBoar)  REFERENCES subjects(exam_board),
  CONSTRAINT student_id_fk      FOREIGN KEY  (student_id)      REFERENCES students(student_id),
  CONSTRAINT studentFirstName_fk FOREIGN KEY (studentFirstName) REFERENCES students(first_name),
  CONSTRAINT studentLastName_fk  FOREIGN KEY (studentLastName)  REFERENCES students(last_name));

答案 3 :(得分:0)

外键约束名称不能与表名的属性相同。

答案 4 :(得分:0)

不确定你想要从第三张桌子到底做什么。但如果目标只是将两个表一起显示,那么只需创建一个视图。

CREATE view entries3 AS 
SELECT 
su.subject_id AS 'Subject_ID',
su.subject_name AS 'Subject_Name',
su.subjectexamboard AS 'Subject_Exam_Board'
st.student_id AS 'Student_ID',
st.studentfirstname AS 'Student_First_Name'
FROM subject su, student st;

然后查询为

SELECT * from entries;
相关问题