2012-02-13 6 views
1

Je ces bases de donnéesDéclare clé étrangère dans MySQL

=== Invoices === 
    id 
    status 
    description 

    === Invoice Items === 
    id 
    invoice_id (FK) 
    item_name 
    description 

Pour ce tableau, je l'ai fait cette commande MySQL

CREATE TABLE IF NOT EXISTS `nt_invoices` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `status` varchar(45) NOT NULL DEFAULT '', 
    `description` text NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ; 


CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `invoice_id` int(11) NOT NULL, 
    `item_name` varchar(45) NOT NULL, 
    `description` text NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `invoice_id` (`invoice_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ; 

Mon problème est que je veux déclarer une clé étrangère dans la invoice_items table et pour faire le invoice_id la clé étrangère de invoices id de la table. Alors, comment écrire cette commande? Toute aide et suggestions seront très appréciées.

Répondre

1

Vous devez avoir le type de moteur innodb pour utiliser des clés étrangères.

CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `invoice_id` int(11) NOT NULL references nt_invoices(id) 
    `item_name` varchar(45) NOT NULL, 
    `description` text NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `invoice_id` (`invoice_id`) 
) ENGINE=INNODB DEFAULT CHARSET=utf8; 

OU si vous souhaitez utiliser la mise à jour en cascade supprimer:

CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `invoice_id` int(11) NOT NULL, 
    `item_name` varchar(45) NOT NULL, 
    `description` text NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `invoice_id` (`invoice_id`), 
FOREIGN KEY (invoice_id) REFERENCES nt_invoices(id) 
    ON DELETE CASCADE 
    ON UPDATE CASCADE, 

) ENGINE=INNODB DEFAULT CHARSET=utf8; 
3

MyISAM ne prend pas en charge les clés étrangères. Vous devez utiliser InnoDB (qui est un meilleur choix dans tous les aspects de toute façon). Ensuite, c'est comme dans n'importe quel autre dialecte SQL:

`invoice_id` int(11) NOT NULL references nt_invoices(id), 

P.S. En outre, toujours utiliser codage utf8 partout. Il vous mordra dans le cul si vous ne le faites pas.

+1

+1 pour attraper la question MyISAM – drnewman

0

Vous pouvez également utiliser la commande ALTER pour déclarer FOREIGN KEY comme suit:

Alter table table_name add foreign key(column_name) 
    references other_table_name(column);