我有一个带有自动增量主键的表:
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)
);
我希望从另一个表的部分填充此表:
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;
我收到一个错误,指出列数不匹配,这是因为主键(这是一个自动递增的值,因此不需要设置)。我该如何解决这个问题?
答案 0 :(得分:25)
您需要明确列出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;
另外,我认为使用显式连接是更好的形式,而不是嵌套选择:
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;
这通常(但并非总是)有助于优化器找到最佳查询计划。
答案 1 :(得分:20)
您只需在插入过程中将主键设置为NULL
。
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 ;