terça-feira, julho 29, 2008

Como criar tabelas com chaves compostas via SQL

Este exemplo foi testado no HSQLDB, vindo direto do projeto free2share:

A tabela principal...:
CREATE TABLE Transfer (
idTransfer INTEGER IDENTITY,
serverID INTEGER,
serverURL VARCHAR,
transferSize INTEGER NOT NULL,
hits_last_hour INTEGER,
hits_total INTEGER,
register_time TIMESTAMP
);

A primeira tabela dependente da principal:
CREATE TABLE TransferBlock (
idTransfer INTEGER NOT NULL,
idTransferBlock INTEGER IDENTITY,
serverBlockId INTEGER,
pointer INTEGER NOT NULL,
datasize INTEGER NOT NULL,
dataoffset INTEGER NOT NULL,
hash INTEGER,
version INTEGER NOT NULL,
FOREIGN KEY (idTransfer) REFERENCES Transfer,
UNIQUE (
idTransfer,
idTransferBlock
)
);

E a terceira tabela, dependente das duas primeiras:

CREATE TABLE TransferBlockLink (
idTransfer INTEGER NOT NULL,
idTransferBlock INTEGER NOT NULL,
idLink INTEGER IDENTITY,
url VARCHAR(255) NOT NULL,
downloaded BOOLEAN NOT NULL,
damaged INTEGER NOT NULL,
FOREIGN KEY (idTransfer) REFERENCES Transfer,
FOREIGN KEY (idTransferBlock) REFERENCES TransferBlock,
UNIQUE (
idTransfer,
idTransferBlock,
idLink
)
);
O resultado deverá ser algo parecido com o do diagrama:

Nenhum comentário: