MySql insert the results of a select

2019-01-18 01:51发布

问题:

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 some data from the t1, but I must be wrong on the syntax.

Thanks for your help

回答1:

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 
  )


回答2:

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;


回答3:

You dont need the VALUES in your query.