--学生表
CREATE TABLE Student
(
student_id int identity primary key,
student_realName varchar(8) not null,
student_userName varchar(20) check(len(student_userName)>=6 and len(student_userName)<=20),
student_password varchar(20) check(len(student_password)>=6 and len(student_password)<=20),
student_identityCard varchar(20) check(len(student_identityCard)=15 and len(student_identityCard)=18),
student_status bit defalut(0) --是否在线
)--教师表
CREATE TABLE Teacher
(
teacher_id int identity primary key,
teacher_realName varchar(8) not null,
teacher_userName varchar(20) check(len(teacher_userName)>=6 and len(teacher_userName)<=20),
teacher_password varchar(20) check(len(teacher_password)>=6 and len(teacher_password)<=20),
teacher_status bit default(0)
)
--用户类型表
CREATE TABLE UserType
(
ut_id int identity primary key,
ut_Name varchar(10) not null
)CREATE TABLE LoginDetails

ld_id int identity primary key,
ld_type int references UserType(ut_id),
ld_userId --这里想引用学生表 或者 教师表的ID字段,意思是只要这个ID是存在的,是学生ID,或者是老师的ID
)该怎样实现啊 高手们

解决方案 »

  1.   

    CREATE TABLE LoginDetails 

    ld_id int identity primary key, 
    ld_type int references UserType(ut_id), 
    ld_userid int,foreign key (ld_userid) references Student(student_id) 
      

  2.   

    2楼的 这样你只引用了一个表啊 CREATE TABLE LoginDetails

    ld_id int identity primary key,
    ld_type int references UserType(ut_id),
    ld_userId int check(ld_userId exists (select student_id from Student) or ld_userId exists (select teacher_id from Teacher))
    )
    这样也不对啊
      

  3.   

    create table tb1(id int  primary key)
    go
    create table tb2(id int  primary key)
    go
    create table tb3
    (
      id int,
      id1 int CONSTRAINT id1 FOREIGN KEY (id1) REFERENCES tb1(id),
      id2 int CONSTRAINT id2 FOREIGN KEY (id2) REFERENCES tb2(id)
    )
    godrop table tb3 , tb2 , tb1/*
    命令已成功完成。
    */
      

  4.   

    不好处理吧。
    还是从数据表结构调整吧。如果学生ID与老师ID不会冲突,而且有用户类型表,建议合并学生表与老师表为一个用户表,再建视图处理。
    如果学生ID与老师ID可能冲突,那么用户类型表应该设置两个字段来对应学生表和老师表。
      

  5.   

    1、为什么不将学生表和教师表合二为一?增加一个字段标识为学生或者教师,如果字段太多可以增加一个字表。
    2、现在这样也可以用
    select a.*,(case when ld_type=教师 then Teacher_realName  else student_realName end) as realName
    from LoginDetails a
    left join 教师表 b on a.ld_userId=b.Teacher_id
    left join 学生表 c on a.ld_userId=c.student_id无非每次查询时关联表比较多,如果字段很多,就要写很长的SQL查询语句。
    既然教师表和学生表的数据要经常一起出现,建议使用合并表。