Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

mysql insert if value not exist in another table

I have two tables that store value as VARCHAR.
I'm populating table and I want just insert values in one of tables if they are not exist in other table.
Something like:

INSERT IF IS EMPTY(SELECT * FROM t1 where v='test') INTO t2 (v) VALUES ('test')

How Can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use some type of INSERT...SELECT query.

Update (after clarification): For example, here is how to insert a row in t2 if a corresponding row do not already exist in t1:

INSERT INTO t2 (v)
  SELECT temp.candidate
  FROM (SELECT 'test' AS candidate) temp
  LEFT JOIN t1 ON t1.v = temp.candidate
  WHERE t1.v IS NULL

To insert multiple rows with the same query, I 'm afraid there is nothing better than

INSERT INTO t2 (v)
  SELECT temp.candidate
  FROM (
      SELECT 'test1' AS candidate
      UNION SELECT 'test2'
      UNION SELECT 'test3' -- etc
  ) temp
  LEFT JOIN t1 ON t1.v = temp.candidate
  WHERE t1.v IS NULL

Original answer

For example, this will take other_column from all rows from table1 that satisfy the WHERE clause and insert rows into table2 with the values used as column_name. It will ignore duplicate key errors.

INSERT IGNORE INTO table2 (column_name)
  SELECT table1.other_column
  FROM table1 WHERE table1.something == 'filter';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...