There is a table. In it, the columns var1 var2 . You need to add records there. Is it possible to implement only SQL checks for the existence of such a record? Just by themselves, the values ​​of var1 and var2 will be repeated, but they should not be together. For example:

1 | 2 1 | 3 2 | 2 2 | 3

When adding if such a combination is, then do nothing. Is it possible? Or without means of another language is not enough?

    4 answers 4

     CREATE TABLE `users` ( `var1` VARCHAR(200) NOT NULL, `var2` VARCHAR(255) NOT NULL, UNIQUE(`var1`, `var2`) ) 

    Referring to http://mysql.ru/docs/man/CREATE_TABLE.html

    • You just need to declare in the table which fields will be unique and will inappropriately load the database with unnecessary requests, it will do everything for you - Barton
    • If you try to violate uniqueness while inserting data into such a database table, an exception is thrown. Not the fact that this is what is necessary for the one who asked. - Modus
    • And you need to check that mysql returns and handle exceptions and then there will be no problems. There is no panacea for all problems, we must deal with them as they are received) - Barton

    If you need a query that is executed without errors

     insert into table select one, two from (select 1 as one, 2 as two) t1 left outer join table t2 on t2.var1=t1.one and t2.var2=t1.two where t2.var1 is null and t2.var2 is null 

      I absolutely agree with the distinguished @Barton . I’ll add a non-literal quote from a book by Thomas Kaite, Oracle Vice President. If a certain option is provided in the DBMS, then by no means try to replace it with your own program code: you will always get worse !!!

        Of course, you need to write a CP, which in the input parameter takes a value that should be inserted into the table, but before inserting it with a select, it is checked.

          insert into table(row) select val1 from other_table where not exist ( select 1 from table where row=val1) 

        maybe wrong, but somehow it should be =)