2010-11-22 96 views
147

我想知道如果有一種方法可以在SQL純粹做到這一點:mysql ::插入表,從另一個表中的數據?

q1 = SELECT campaign_id, from_number, received_msg, date_received 
    FROM `received_txts` WHERE `campaign_id` = '8'; 
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)  
    VALUES(q1.campaign_id, q1.from_number, q1.received_msg, q1.date_received); 

注: Q1將返回大約30K行。

有什麼辦法可以做到我在上面直sql嗎? 只需從一個表(基本上是一個原始數據表)直接提取數據並插入另一個表(基本上是一個處理過的數據表)?

回答

307
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date) 
SELECT campaign_id, from_number, received_msg, date_received 
    FROM `received_txts` 
WHERE `campaign_id` = '8' 
+0

完美:)我很接近... ish。將盡快接受答案 – Hailwood 2010-11-22 02:06:13

+1

+1只有幾秒鐘才能擊敗:-) – InSane 2010-11-22 02:07:42

+1

@InSane:1)給出答案2)更正問題格式。下次不要錯過訂單;-) – zerkms 2010-11-22 02:09:46

19

爲全行

insert into xyz select * from xyz2 where id="1";

選定列

insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";
+0

如果已存在具有匹配主鍵的現有記錄,整行方法將失敗。 – HotN 2016-12-14 15:50:22

-1

你可以不喜歡它,如下:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `vote`, `vote_date`) 
SELECT `campaign_id`, `from_number`, `received_msg`, `date_received` FROM `received_txts` WHERE `campaign_id` = '8' 
+6

這不正是zerkms在5年前寫的(除了列名和表名外)嗎? – user276648 2016-03-18 07:54:53

1
INSERT INTO Table1 SELECT * FROM Table2 
5

通過zerkms的回答是正確的方法。但是,如果有人看在表中插入更多的額外的列,那麼你可以從下面得到它:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`) 
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8' 

在上面的查詢中,有2個名爲電子郵件 & CURRENT_TIME額外列。

+1

如果我想插入三行數據,其中的值與select中的值相同,但添加的「additional」列的值不同,例如email和current_time? – xxstevenxo 2018-02-01 02:55:43

相關問題