2013-10-10 19 views
0

두 테이블이 있다고 가정 해 봅시다. 다중 ID SQL 쿼리

첫번째

:

id thing1 thing2 

번째 : id_fo이 첫번째 테이블 의존

id_fo other_thing 

.

두 테이블에 thingS를 삽입해야하지만 PHP에서는 mysql 요청 (예 : pdo)에서 마지막 삽입 ID를 모두 가져올 수 있습니까?

내가 한 쿼리에서 30 행을 가진다면 30 개의 새 ID를 갖게됩니다.

어떻게 두 번째 SQL 쿼리를 수행 할 수 있습니까?

+0

... 당신은을 재구성 할 수 있습니다 질문이나 필요한 것을 보여줄 수 있습니다 ... – Nathan

+0

더 이상 명시적일 수 없습니다. 첫 번째 테이블에 30 개의 행을 추가하면 어떻게 모든 ID를 얻을 수 있습니까? – Cherche

답변

1

: 쿼리를 호출

Start transaction 
    insert into table1 (thing1, thing2) values (thingS,thingS2) 
    lastidtable1 = lastinsertedid(); 
    insert into table2 (id_fo, other_thing) values (lastidtable1,thingS); 
    lastidtable2 = lastinsertedId(); 
commit; 

위 라인의 모든 PHP를해야 코드입니다.

0

INSERT 및 UPDATE에서 데이터 세트가 반환되지 않으면 타임 스탬프 유형의 INSERTED 열을 추가하고 DEFAULT를 CURRENT_TIMESTAMP로 설정하고 가장 큰 타임 스탬프 값을 가진 모든 행을 선택할 수 있습니다.

1

이 같은 것을 찾고 계십니까? 사이비 코드에서

$main_data = array('dino', 'babu', 'john'); 

    foreach($main_data as $main) { 

     // Insert main to 1st table 
     mysql_query("MY INSERT QUERY TO TABLE 1"); 

     // Get the last insert id 
     $new_id = mysql_insert_id(); 

     // Insert the sub data to 2nd table using the insert id 
     mysql_query("MY INSERT QUERY TO TABLE 2 USING $new_id "); 
    } 
+0

글쎄, 이런 종류의 요청은 많은 고통을 한꺼번에 삽입해야하는 즉시 고통 스럽다. 이 INSERT INTO 테이블 (thing1, thing2) VALUES ('test', 'test'), ('test2', 'test2')와 같은 것을 상상해보십시오. 하지만 어쨌든 왜 – Cherche

+0

그래서 배열이나 뭔가로 ids를 삽입해야합니까 ??? ??? – Dino

0

당신은 하나의 삽입 과정이 사이비 코드와 같은 일을 할 수있는 시간에 일어나고 있다는 것을 보장 할 수있는 경우 :

당신은 더 명시 할 필요가
$max1=select max(id) as max1 from table; 
insert into table .... 
$num_inserted_rows=number of inserted rows. 
$max2=select max(id) as max2 from table; 
if(($max2-$max1) == $num_inserted_rows){ 
    $lastid=select last_insert_id(); 
    $inserted_ids=range($lastid-$num_inserted_rows,$lastid); 
}