How to insert with where clause

后端 未结 4 1412
时光取名叫无心
时光取名叫无心 2020-12-07 02:32

I am using the following query to insert values into one field in table A.

insert
into A (name)
values (\'abc\')
where
   A.id=B.code
   and B.dept=\'hr\' ;
         


        
相关标签:
4条回答
  • 2020-12-07 03:09

    You should rather use UPDATE, if you want to change the value of the field in records you select using the WHERE clause.

    0 讨论(0)
  • 2020-12-07 03:14
    MERGE
    INTO a
    USING (
      SELECT *
      FROM b
      WHERE b.dept = 'hr'
    )
    ON a.id = b.code
    WHEN NOT MATCHED THEN
      INSERT (id, name)
      VALUES (code, 'abc')
    WHEN MATCHED THEN
      UPDATE
      SET name = 'abc'
    
    0 讨论(0)
  • 2020-12-07 03:18

    the insert part should be ok

    insert
    into A (name)
    values ('abc')
    

    it really depends on what you are trying to achieve with the where clause and the B table reference.

    0 讨论(0)
  • 2020-12-07 03:18
    INSERT INTO A (name)
    SELECT name 
    FROM A as a
    LEFT JOIN B as b ON b.id=a.id
    WHERE a.id=b.code AND b.dept='hr'
    

    A is the first Table then B is the Second table JOIN together using LEFT JOIN then name is the column. this is what he wants to do on his question.

    This is what "INSERT SELECT STATEMENT" do.

    Query that can Insert while doing a select and combining a WHERE and JOIN.

    INSERT TABLE1 (column1)
    SELECT column1
    FROM TABLE1 as a
    LEFT JOIN TABLE2 as b ON b.column1=a.column1
    WHERE a.column2=b.column3 AND b.column4='hr'
    
    0 讨论(0)
提交回复
热议问题