2013-09-01 2 views
1

두 테이블 A와 B가 있습니다. 테이블 B에 새 행을 삽입 할 때 테이블 A의 레코드에 대한 참조로 FK를 삽입하려면 어떻게해야합니까? 내가 삽입을 수행 할 때행에 외래 키를 삽입하는 방법은 무엇입니까?

-- 
-- 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를 얻으려는 생각이 들었어. 하지만 저는 'Constituent'crud 방식으로 섹터 ID를 얻기 위해 두 번째 읽기를 할 것입니다. – TheMightyLlama

답변

1

것은, 당신은 매개 변수없이 사용하는 경우는 마지막 자동으로 생성 된 값을 반환 last_insert_id() 기능을 사용할 수있는 테이블 A에 삽입하기 위해, 테이블 B에 삽입 한 후 기본 키 값을 얻을 수있을하려면 예를 들어

:

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

그는 AUTO_INCREMENT 열에 대해 설정된
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"); 
관련 문제