MySQL direct INSERT INTO with WHERE clause

前端 未结 6 2037
梦如初夏
梦如初夏 2020-12-15 09:04

I tried googling for this issue but only find how to do it using two tables, as follows,

INSERT INTO tbl_member
SELECT Field1,Field2,Field3,... 
FROM temp_ta         


        
相关标签:
6条回答
  • 2020-12-15 09:29

    Example of how to perform a INSERT INTO SELECT with a WHERE clause.

    INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2
    
    0 讨论(0)
  • 2020-12-15 09:31

    The INSERT INTO Statement
    The INSERT INTO statement is used to insert a new row in a table.
    SQL INSERT INTO Syntax

    It is possible to write the INSERT INTO statement in two forms.

    The first form doesn't specify the column names where the data will be inserted, only their values:

    INSERT INTO table_name
    VALUES (value1, value2, value3,...)
    

    The second form specifies both the column names and the values to be inserted:

    INSERT INTO table_name (column1, column2, column3,...)
    VALUES (value1, value2, value3,...)
    
    0 讨论(0)
  • 2020-12-15 09:43

    If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:

    INSERT INTO tbl_member 
    (Field1,Field2,Field3,...) 
    SELECT a.Field1,a.Field2,a.Field3,... 
    FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a 
    LEFT JOIN tbl_member AS b 
    ON a.Field1 = b.Field1 
    WHERE b.Field1 IS NULL
    

    The record to be inserted is in the new value fields.

    0 讨论(0)
  • 2020-12-15 09:45

    you can use UPDATE command.

    UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id
    
    0 讨论(0)
  • 2020-12-15 09:52

    INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.

    The first syntax is already correct.

    0 讨论(0)
  • 2020-12-15 09:55

    INSERT syntax cannot have WHERE but you can use UPDATE.

    The syntax is as follows:

    UPDATE table_name
    
    SET column1 = value1, column2 = value2, ...
    
    WHERE condition;
    
    0 讨论(0)
提交回复
热议问题