Insert line only if line doesn't exist
I am creating a counter. I have an article directory and unique visitor tracking. When a visitor arrives, I insert the article ID and my IP address into the database. First I check if the ip exists for the article id, if the ip doesn't exist I do an insert. These are two requests - is there any way to make this one request
Also, I am not using stored procedures. I am using normal inline sql
source to share
Here are some options:
INSERT IGNORE INTO `yourTable`
SET `yourField` = 'yourValue',
`yourOtherField` = 'yourOtherValue';
from the MySQL reference manual: "If you use the IGNORE keyword, errors that occur when executing an INSERT statement are handled instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or a PRIMARY KEY value in a table raises a duplicate key error, and the statement aborts. ".) If the entry does not already exist, it will be created.
Another variant:
INSERT INTO yourTable (yourfield,yourOtherField) VALUES ('yourValue','yourOtherValue')
ON DUPLICATE KEY UPDATE yourField = yourField;
Doesn't throw errors or warnings.
source to share
Not with SQL Server. With T-SQL, you need to check for the existence of a row, then use both INSERT and UPDATE.
Another option is to try UPDATE first and then check the row count to see if the record has been updated. If not, then INSERT. Given a 50/50 chance of having a row, you have completed one query 50% of the time.
MySQL has an extension called REPLACE which has the capability you are looking for.
source to share