开发者

MySql insert the results of a select

开发者 https://www.devze.com 2023-01-31 16:40 出处:网络
I would like to know if I can run a request like that: INSERT INTO t2 (a, b) VALUES ( SELECT a, b FROM `t1` AS o

I would like to know if I can run a request like that:

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

The idea is to fill the t2 with som开发者_StackOverflowe data from the t1, but I must be wrong on the syntax.

Thanks for your help


You don't use the VALUES keyword when inserting from a SELECT statement.

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


remove the values

like

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

OR a more readble format

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;


You dont need the VALUES in your query.

0

精彩评论

暂无评论...
验证码 换一张
取 消