MySQL使用条件语句插入查询

时间:2014-03-14 20:01:20

标签: mysql sql mysql-workbench

我创建了一个包含两个表(学生和教师)的MySQL模式。

1. Students are given a student number when they join the school.
   This is stored along with their name, date of birth, and the date they joined
   the school.

2. All instructors are also students, but clearly, not all students are
   instructors. In addition to the normal student information, for all 
   instructors, the date that they start working as an instructor must be
   recorded, along with their instructor status (compensated or volunteer). 

我的架构:

STUDENT

+---------------+
| ID            | PK
+---------------+
| LNAME         |
+---------------+
| FNAME         |
+---------------+
| MNAME         |
+---------------+
| BDAY          |
+---------------+
| JOIN_DATE     |
+---------------+
| IS_INSTRUCTOR |
+---------------+

讲师

+---------------+
| ID            | PK
+---------------+
| STUDENT_ID    | FK
+---------------+
| INSTR_STATUS  | (compensated or volunteer)
+---------------+
| DATE_WORKED   |
+---------------+

当我插入到STUDENT TABLE中时,如果IS_INSTRUCTOR = 1(意味着是真的)INSTRUCTOR TABLE(STUDENT_ID)将具有STUDENT.ID吗?

或者你的家伙有更好的桌面设计? TIA

4 个答案:

答案 0 :(得分:1)

我不确定为什么学生表中需要is_instructor字段。每次添加或删除instructor表中的记录时,都需要更新它。如果您需要查看特定学生是否是教师,student_id上的简单散列连接就足够了。但我看到的选项:第一个是使用存储过程,第二个选项只是将单独的插入包装到一个事务中。

除非有特定的应用要求,否则我会删除计算字段is_instructor。虽然代理(或人工)密钥可能很有用,但对于当前设计,我会从讲师表中删除主键id,并使student_id成为主键,它也是student表的外键。 。

答案 1 :(得分:0)

......中的某些内容......

INSERT INTO INSTRUCTOR (STUDENT_ID, INSTR_STATUS, DATE_WORKED)
SELECT ID, 'volunteer', NOW() 
FROM STUDENT
WHERE IS_INSTRUCTOR = 1

您可能想重新考虑您的设计。

答案 2 :(得分:0)

我认为触发器是目前最好的想法。但这个模型有点混乱。为一切创建一个表不是更好吗?

+---------------+  
| ID            | PK  
+---------------+  
| LNAME         |  
+---------------+  
| FNAME         |  
+---------------+  
| MNAME         |  
+---------------+  
| BDAY          |  
+---------------+  
| JOIN_DATE     |  
+---------------+  
| IS_INSTRUCTOR |  
+---------------+  
| INSTR_STATUS  | (compensated or volunteer)  
+---------------+  
| DATE_WORKED   |  
+---------------+  

答案 3 :(得分:0)

This link may help you

您可以使用WHERE子句,如:

WHERE IS_INSTRUCTOR = 1