2013-07-21 13 views
13

Ho una tabella con una chiave primaria di incremento automatico:MySQL inserire nella tabella con incremento automatico, mentre la selezione di un'altra tabella

create table rt_table 
(
    rtID int PRIMARY KEY AUTO_INCREMENT, 
    rt_user_id BIGINT,    /*user being retweeted*/ 
    rt_user_name varchar(70),  /*user name of rt_user_id*/ 
    source_user_id BIGINT,   /*user tweeting rt_user_id*/ 
    source_user_name varchar(70), /*user name of source_user_id*/ 
    tweet_id BIGINT,     /*fk to table tweets*/ 

    FOREIGN KEY (tweet_id) references tweets(tweet_id) 
); 

desidero popolare questa tabella da parte di un altro tavolo:

insert into rt_table 
select rt_user_id, (select user_name from users u where u.user_id = t.rt_user_id), 
     source_user_id, (select user_name from users u where u.user_id = t.source_user_id), 
     tweet_id 
    from tweets t 
where rt_user_id != -1; 

Viene visualizzato un errore che indica che il numero di colonne non corrisponde, a causa della chiave primaria (che è un valore autoincrementato e quindi non deve essere impostato). Come faccio a evitare questo?

risposta

20

È necessario elencare esplicitamente le colonne nella dichiarazione insert:

insert into rt_table (rt_user_id, rt_user_name, source_user_id, source_user_name, tweet_id) 
select rt_user_id, (select user_name from users u where u.user_id = t.rt_user_id), 
     source_user_id, (select user_name from users u where u.user_id = t.source_user_id), 
     tweet_id 
    from tweets t 
where rt_user_id != -1; 

Inoltre, penso che è la forma meglio usare esplicita unisce, piuttosto che seleziona nidificati:

insert into rt_table (rt_user_id, rt_user_name, source_user_id, source_user_name, tweet_id) 
    select t.rt_user_id, u.user_name, t.source_user_id, su.user_name, t.tweet_id 
    from tweets t left outer join 
     users u 
     on t.rt_user_id = u.user_id left outer join 
     users su 
     on t.source_user_id = su.user_id 
    where rt_user_id != -1; 

Questo spesso (ma non sempre) aiuta l'ottimizzatore a trovare il miglior piano di query.

12

È sufficiente impostare la chiave primaria per NULL durante l'inserto.

INSERT INTO rt_table 
SELECT 
    NULL, 
    rt_user_id, 
    (SELECT 
    user_name 
    FROM 
    users u 
    WHERE u.user_id = t.rt_user_id), 
    source_user_id, 
    (SELECT 
    user_name 
    FROM 
    users u 
    WHERE u.user_id = t.source_user_id), 
    tweet_id 
FROM 
    tweets t 
WHERE rt_user_id != - 1 ; 
Problemi correlati