2013-09-01 32 views
1

我有兩個表A和B.當向表B中插入新行時,如何插入FK作爲表A中記錄的引用?如何在一行中插入一個外鍵?

我有兩個見下表:

-- 
-- Table structure for table `sector` 
-- 

CREATE TABLE IF NOT EXISTS `sector` (
    `sector_id` int(11) NOT NULL AUTO_INCREMENT, 
    `sector_name` varchar(100) NOT NULL, 
    `sector_url` varchar(500) NOT NULL, 
    PRIMARY KEY (`sector_id`), 
    UNIQUE KEY `sector_id` (`sector_id`,`sector_name`,`sector_url`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 


CREATE TABLE IF NOT EXISTS `constituent` (
    `constituent_id` int(11) NOT NULL AUTO_INCREMENT, 
    `constituent_name` varchar(100) DEFAULT '', 
    `constituent_ticker` varchar(10) NOT NULL, 
    `constituent_isin_number` varchar(50) DEFAULT '', 
    `constituent_currency` varchar(10) DEFAULT '', 
    `sector_id` int(11) NOT NULL, 
    PRIMARY KEY (`constituent_id`), 
    KEY `sector_id` (`sector_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 


-- 
-- Constraints for table `constituent` 
-- 
ALTER TABLE `constituent` 
    ADD CONSTRAINT `constituent_ibfk_1` FOREIGN KEY (`sector_id`) REFERENCES `sector` (`sector_id`); 

當我做一個插入,我怎麼能結構中的查詢,這樣當我插入到表「成分」,我使用的是主'部門'的關鍵?

INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sectorFK) 
values ("the name", "the ticker", "the number", "the currency", "the foreign key???") 
+0

您必須先以某種方式獲取'sector_id' –

+0

只需將它的外鍵值 - 一個普通整數值即可。它可以像任何其他值一樣插入。 – halfer

+0

是的,我正在考慮以某種方式獲得部門ID。但我想我會再讀一遍,以獲得「組成部分」污染方法中的扇區ID ...... – TheMightyLlama

回答

1

爲了能夠插入到表B後得到一個主鍵值,以便將其插入到表A,你可以使用last_insert_id()功能,不帶參數使用時返回最後自動生成的值這是將其設置爲AUTO_INCREMENT柱:

例如:

insert into B(col) 
    values(1); 

insert into A(t1_id, col) 
    values(last_insert_id(), 2); 

insert into A(t1_id, col) 
    values(last_insert_id(), 3); 

SQLFIddle Demo

0

假設有一個sector_name爲'sector 1'的扇區,你可以這樣做。

INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sector_id) (select 'the name', 'the ticker', 'the number', 'the currency', sector_id from sector where sector_name = "sector 1"); 
相關問題