如何像这样创建表层次结构

时间:2015-07-22 13:17:28

标签: mysql

我有一张测试表,其中列出了医院可用的所有测试,医院还提供了测试组作为包。 测试表的一个例子如下......

Table : Tests
Id    Name
1     Test1
2     Test2
3     Test3

我想创建一个名为Packages的表,它将在组中进行这些测试,我想创建这些测试的组:

Table Packages:

Package 1   has     
Test 1
Test 2
and so on....

Package 2    has      
Test 3
Test 2
Test 1
and so on....

Package 3      
Test 3
Test 1
and so on....

我怎样才能以更好的方式做到这一点

1 个答案:

答案 0 :(得分:1)

create table tests
(   id int auto_increment primary key,
    name varchar(200) not null
);

create table packages
(   id int auto_increment primary key,
    name varchar(200) not null
);

create table tp_junction
(   -- if the test and package intersect, insert a row here
    id int auto_increment primary key,
    testId int not null,
    pkgId int not null,
    unique key (testId,pkgId),  -- limits 1 combo to elimiate residue

    -- referential integrity, parents must exist:
    CONSTRAINT fk_test_par FOREIGN KEY (testId) REFERENCES tests(id),
    CONSTRAINT fk_pkg_par FOREIGN KEY (pkgId) REFERENCES packages(id)
);