SQL Insert row if not exsist
I am VERY new to mySQL, please bear with me.
I have an array that is always growing, lets say for now it has 4 items in it. I need the sql to search the table and insert a new row for each item in the array, but only if its a new item (meaning it hasn't already been inserted). There are 5 columns in the table, and each item in the row needs to be a variable so i can pass dynamic data through.
I know this is way off but what i have now is something like this.
$array_count = array(1,2,3,4);
$var1 = 'value 1';
$var2 = 'value 2';
$var3 = 'value 3';
$var4 = 'value 4';
$var5 = 'value 5';
$sql = "INSERT INTO membership_levels VALUES ('".$var1."', '".$var2."', '".$var3."', '".$var4."', '".$开发者_如何学Pythonvar5."')";
Mysql - ON DUPLICATE KEY
If you database is MySql you can use like Brad Christie has wrote with the Insert On Duplicate. You will need to have a primary key on the 5 columns if you want inserting only if they are all the same value.
Your $sql will change to :
$sql = "INSERT INTO membership_levels(a,b,c,d) VALUES VALUES ('".$var1."', '".$var2."', '".$var3."', '".$var4."', '".$var5."')
ON DUPLICATE KEY UPDATE a=VALUES(a), b=VALUES(b), c = VALUES(c), d = VALUES (d);"
Mysql - Replace
You can also use the Replace key word. If the row exist, it will delete it for you and insert the new one.
$sql = "REPLACE INTO membership_levels VALUES ('".$var1."', '".$var2."', '".$var3."', '".$var4."', '".$var5."')";
MsSql
If you database is MsSql (Sql server) it's 2 queries :
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)"
The best way if SQL Server would be to use Stored Procedure.
Looking for INSERT ... ON DUPLICATE UPDATE syntax?
I would need the PK (Primary Key) to give you an exact query to run with...
Assuming this is MySQL given PHP tag
Take a look at this article which I believe may answer your question: http://www.xaprb.com/blog/2005/09/25/insert-if-not-exists-queries-in-mysql/
It shows several possible ways of writing a SQL query to overcome the lack of "IF NOT EXISTS" syntax. Note that if you were using SQL Server, you could write IF NOT EXISTS.
精彩评论