简体   繁体   English

mysql插入,如果另一个表中不存在值

[英]mysql insert if value not exist in another table

I have two tables that store value as VARCHAR .我有两个表将值存储为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?我怎样才能做到这一点?

You need to use some type ofINSERT...SELECT query.您需要使用某种类型的INSERT...SELECT查询。

Update (after clarification): For example, here is how to insert a row in t2 if a corresponding row do not already exist in t1 :更新(澄清后):例如,如果相应的行在t1不存在,这里是如何在t2插入一行:

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 .例如,这将从table1中满足WHERE子句的所有行中获取other_column并将行插入table2 ,其值用作column_name It will ignore duplicate key errors.它将忽略重复的键错误。

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

for insertion of Multiple columns you can try this.对于插入多列,你可以试试这个。

INSERT INTO table_1 (column_id,column_2,column_3,column_4,column_5)
 SELECT
    table_2.*
FROM
    table_2
LEFT JOIN table_1 ON table_1.column_id = table_2.column_id
WHERE
    table_1.column_id IS NULL;
INSERT IGNORE INTO table_1(col1,col2,col3,col4)
  SELECT table_2.*
  FROM table_2;

The above statement does the perfect job in your scenario.上面的语句在您的场景中做得很完美。

  1. Line 1: States the table where you want the data to be replicated whilst ignoring any key constraints.第 1 行:说明您希望复制数据的表,同时忽略任何关键约束。
  2. Line 2: selects the table and columns where data should come from第 2 行:选择数据应来自的表和列
  3. Line 3: states the table from where data is to be replicated from第 3 行:声明要从中复制数据的表

Kinda ghetto.. but works.有点贫民窟..但有效。 Assumes that you are inserting a static value into 'col'假设您将静态值插入到“col”中

INSERT INTO t1 (col)
SELECT 'test' 
  FROM t2
 WHERE (SELECT count(*) FROM t2 WHERE v='test') = 0;
$result = mysql_query("SELECT * FROM t1 WHERE v='test'");
if(mysql_num_rows($result) == 0){
    mysql_query("INSERT INTO t2 (v) VALUES ('test')");
}

Haven't been using mysql for a while so these functions are deprecated, but this is how I should do it.有一段时间没有使用 mysql,所以这些功能已被弃用,但我应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM