SQL包和通道关系

时间:2015-06-18 02:05:19

标签: mysql sql

我在查找Package和Channel之间的多对多关系时遇到了问题。每个频道属于一个包,但一次只能包含1个以上的包。

IE:频道1属于包1,2,3,4,5     频道2属于Package 2,5

等等。如何编写表来创建这种关系?到目前为止,我有:

CREATE TABLE Channel
(
ChannelID        NUMBER(10) CONSTRAINT PK_Channel PRIMARY KEY,
ChannelName      VARCHAR2(12) NOT NULL,
ChannelDesc      VARCHAR2(20) NOT NULL,
ChannelNumber    NUMBER(3) NOT NULL,
SupID            NUMBER(2) CONSTRAINT FK_Channel_Supplier REFERENCES Supplier (SupID),
PackageID        NUMBER(5) CONSTRAINT FK_Channel_Package REFERENCES Package (PackageID)
);

INSERT INTO CHANNEL
VALUES(0001, 'Channel 1', '1st Channel', 01, 10001);
INSERT INTO CHANNEL
VALUES(0002,'Channel 2', '2nd Channel', 02, 10001);
INSERT INTO CHANNEL
VALUES(0003, 'Channel 3', '3rd Channel', 03, 10002);
INSERT INTO CHANNEL
VALUES(0004, 'Channel 4', '4th Channel', 04, 10003);
INSERT INTO CHANNEL
VALUES(0005, 'Channel 5', '5th Channel', 05, 10004);
INSERT INTO CHANNEL
VALUES(0006, 'Channel 6', '6th Channel', 06, 10001);
INSERT INTO CHANNEL
VALUES(0007, 'Channel 7', '7th Channel', 07, 10004);
INSERT INTO CHANNEL
VALUES(0008, 'Channel 8', '8th Channel', 08, 20005);

CREATE TABLE Package
(
PackageID            NUMBER(10) CONSTRAINT PK_Package PRIMARY KEY,
PackageDescrip       VARCHAR2(25) NOT NULL,
PackageFee           NUMBER(3) DEFAULT '0',
);

INSERT INTO PACKAGE
VALUES(01, 'Movies Galore', 30);
INSERT INTO PACKAGE
VALUES(02, 'News Globe', 30);
INSERT INTO PACKAGE
VALUES(03, 'Total Watcher', 40);
INSERT INTO PACKAGE
VALUES(04, 'Couch Potato', 50);

1 个答案:

答案 0 :(得分:0)

我会添加一个额外的表来处理通道到包的关系,并拉出Channel表中的PackageID列。

CREATE TABLE PackageChannel
(
    PackageChannelID            NUMBER(10) CONSTRAINT PK_PackageChannel PRIMARY KEY,
    PackageID       NUMBER(10),
    ChannelID       NUMBER(10)
);

然后在select语句中处理关系

SELECT PackageID FROM PackageChannel WHERE ChannelID = 0001;