2010-12-17 121 views
26

的結果,我想知道我是否可以運行這樣的請求:MySql的插入的選擇

INSERT INTO t2 (a, b) 
VALUES (
SELECT a, b 
FROM `t1` AS o 
WHERE o.id NOT 
IN (
    SELECT a 
    FROM t2 
) 
) 

的想法是,以填補從T1一些數據T2,但我一定是錯的在語法上。

感謝您的幫助

回答

43

SELECT語句插入,當你不使用VALUES關鍵字。

INSERT INTO t2 (a, b) 
SELECT a, b 
FROM `t1` AS o 
WHERE o.id NOT 
IN (
    SELECT a 
    FROM t2 
) 
5

刪除values

INSERT INTO t2 (a, b) 
SELECT a, b 
FROM `t1` AS o 
WHERE o.id NOT 
IN 
(
    SELECT a 
    FROM t2 
); 

或更readble格式

INSERT INTO t2 (a, b) 
SELECT o.a, o.b 
FROM `t1` AS o 
LEFT JOIN t2 ON o.id=t2.a 
WHERE t2.a IS NULL;