INSERT in table1 based on condition on table2 – MySQL

All we need is an easy explanation of the problem, so here it is.

I have two tables t1 and t2 in MySQL. I’ve to insert records into t1 when the following conditions on t2 are TRUE: version != -1 AND login = "xyz".

I tried this query but no luck:

INSERT INTO t1(name, login, email, add)
SELECT "john", "john159", "[email protected]", "dallas"
SELECT version, login 
WHERE login = "john159" 
AND version != -1);

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Please try the following, I haven’t executed the same on the editor but I hope you will get a different idea with it.

INSERT INTO T1(name, login, email) 
        SELECT "john", "john159", "[email protected]"
            FROM dual
                                 WHERE login = "john159" 
                                   AND version  <> -1)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply