Search code examples
mysqlsqlsql-serversql-insertsql-query-store

SQL Query with a Condition between 2 Tables


I'm trying to:

1) Find whether 1 object contains the same Username and Password that I have inputted, in Table 1

2) IF there is an object that contains the same Username and Password then

3) Carry out an INSERT statement inside Table 2.

So far the best I've got is:

(CASE WHEN table1 WHERE Username='myusername' AND Password='mypassword' 
    THEN ( INSERT INTO table2(things) VALUES('mythings') ) 
 ELSE Null END)

Solution

  • You could select the string to insert from table1 and move the condition to the where clause. This way you have a statement that either inserts one record if the username and passowrd match, or no records if they don't:

    INSERT INTO table2(things)
    SELECT      'mythings'
    FROM        table1
    WHERE       Username='myusername' AND Password='mypassword'