how to use if not exists while inserting a row mysql - mysql

The thing that i want to do is to check if there is a same row and if not to insert a new row to the table.
In that case, how can i use if not exists ?
INSERT INTO `facebook` (`ID`,`fb_id`,`label_id`,`page_ids`,`token`) VALUES (NULL,'". $session['id'] ."','$id','','". $access_token ."')
For example, in that query, i want to check if there is a row with the same label_id record and if not, execute that query.
any help ?
thanks

You can use the INSERT IGNORE INTO ... syntax. When using this, duplicate key errors are treated as warnings and the statement will return without having inserted the affected row.

INSERT INTO `facebook` (`ID`,`fb_id`,`label_id`,`page_ids`,`token`)
SELECT NULL, '". $session['id'] ."', '$id', '', '". $access_token ."'
FROM DUAL
WHERE NOT EXISTS (SELECT 'x' FROM facebook WHERE label_id = '$id')
I think FROM DUAL is optional, but I'm an Oracle guy. :)

User Insert Into to ignore duplicates:
INSERT IGNORE INTO `facebook`
SET `ID` = null,
`fb_id` = '". $session['id'] ."',
`label_id` = '$id',
`page_ids`='',
`token`='". $access_token ."';

Related

update table with history keeper of the updated records in a new column

I need to log the updated columns into an existing empty column in which it should appear "Updated" or "Not Updated". I am running this query in MS Access.
Below find an example for my update query (which works) and code for the trigger (not sure i need one, or if i'm using it correctly)
update my_table
set col_i_need_to_set = 'value'
WHERE another_col like 'some_text'
and another_col2 LIKE 'some_other_text'
and another_col3 LIKE 'text'
CREATE OR REPLACE TRIGGER historyKeeper
AFTER UPDATE my_table
FOR EACH ROW
BEGIN
IF( UPDATING( 'col_i_need_to_set' ) )
THEN
INSERT INTO my_table( column_in_which_i_want_to_insert, column_value )
VALUES( 'Updated');
else
INSERT INTO my_table( column_in_which_i_want_to_insert, column_value )
VALUES( 'Not updated');
END IF;
END;
Thank you
actually, found the solution. after set col_i_need_to_set = 'value' I just need to add , column_in_which_i_want_to_insert = 'UPDATED' Maybe this will help someone

MySQL - "insert if not exists" query?

I'm trying to write a MySQL query which will update a blog post view counter if the user has not visited the post in the last 24 hours. I'm trying to write something like this (but this does not work):
IF EXISTS (
SELECT 1
FROM `posts-views`
WHERE
`ip` = '".$_SERVER['REMOTE_ADDR']."'
AND
`time` > ".($time-60*60*24)."
AND
`post` = $id
) THEN
NULL
ELSE
INSERT INTO `posts-views`
(`post`, `time`, `ip`, `user`)
VALUES
($id, $time, '".$_SERVER['REMOTE_ADDR']."', $me)
What's the correct way to fix the query?
From what I see you cannot use INSERT IGNORE in that case, but something like following should do the job :
INSERT INTO `posts-views`
(`post`, `time`, `ip`, `user`)
SELECT $id, $time, '".$_SERVER['REMOTE_ADDR']."', $me
FROM dual
WHERE NOT EXISTS (
SELECT 1
FROM `posts-views`
WHERE
`ip` = '".$_SERVER['REMOTE_ADDR']."'
AND
`time` > ".$time-60*60*24."
AND
`post` = $id
)
I completely omit escaping variables which definitely should be done in real code.
UPDATED - added from dual to avoid syntax error

mysql REPLACE INTO and optional values IFNULL

I'm trying to do something like this inside of a stored procedure:
REPLACE INTO mytable
SET myid = `IDvalue`, mytitle = `sMyTitle`, myoptionalvalue = IFNULL(`sMyOptValue`, myoptionalvalue);
But not seems to work, any idea how to do this?
Thanks!
The REPLACE INTO syntax works exactly like INSERT INTO except that any old rows with the same primary or unique key is automaticly deleted before the new row is inserted.
This means that instead of a WHERE clause, you should add the primary key to the values beeing replaced to limit your update.
REPLACE INTO myTable (
myPrimaryKey,
myColumn1,
myColumn2
) VALUES (
100,
'value1',
'value2'
);
...will provide the same result as...
UPDATE myTable
SET myColumn1 = 'value1', myColumn2 = 'value2'
WHERE myPrimaryKey = 100;

mysql insert with conditions

I have a mysql database and a form that inserts stuff into it. I would like to prevent adding a row if there was a row where the Status column equaled "New" or "Redeploy" and is the same $tag (which is what they are entering in to the area of the form)
Basically i want to prevent people from adding a entry if that $tag already was there with a status of "new" or "redeploy". kind of hard to explain
here is my current query any assistance or ideas would be appreciated.
mysql_query ("INSERT INTO Assets (`Badge`, `First Name`, `Last Name`, `Service Tag`, `Asset Tag`, `Status`, `Employee Status`, `Username`, `deleted`)
VALUES('$badge', '$first', '$last', '$tag', '$asset', '$status', '$estatus', '$user', '$deleted') ") or die (mysql_error());
The best way to do this would be to use a check constraint on the table. That way your condition will always be enforced, no matter how the insert/update is made.
http://www.w3schools.com/sql/sql_check.asp
For something like this you'd probably want to create a function as well. So your function would look like:
CREATE FUNCTION CheckAssetRows(#Tag VARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE #NumInvalidRows INT
SELECT #NumInvalidRows = COUNT(*)
FROM Asset
WHERE [Service Tag]=#Tag
AND [Status] in ('New', 'Redeploy')
RETURN #NumInvalidRows
END
GO
And your check is easy:
ALTER TABLE ASSET
ADD CONSTRAINT chk_Tag CHECK(CheckAssetRows([Service Tag]) = 0)

If not exist insert into table mysql problem

I am trying to insert into my table, but only if the information doesn't exist already.
This works:
$sql = //"if not exists (select `id` from friends where `id` = :id) " . //ERROR!
"insert into `friends` (`id`, `fb_id`, `name`, `id2`, `fb_id2`, `name2`) " .
"values (:id, :fb_id, :name, :id2, :fb_id2, :name2)";
try
{
$stmt = $this->db->prepare($sql);
if (!$stmt)
{
$errorcode = (string)
$stmt->errorCode();
trigger_error("mysql errorcode : " . $errorcode, E_USER_ERROR);
$data = array( "note" => "mysql error code: " . $errorcode );
return json_encode( $data );
}
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':fb_id', $fb_id, PDO::PARAM_INT);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':id2', $id2, PDO::PARAM_INT);
$stmt->bindParam(':fb_id2', $fb_id2, PDO::PARAM_INT);
$stmt->bindParam(':name2', $name2, PDO::PARAM_STR);
$result = $stmt->execute();
$stmt->closeCursor();
}
catch (Exception $e)
{
die ($e->getMessage() );
}
I tried if not exists ( select id ... etc as commeted out in the first line, but that didn't work. It returned error code 00000 with (string) $stmt->errorCode();, I googled it and it means: to many mysql connections, this can't be the problem as other queries work fine.
How do I insert into the table when not exist and how do I get mysql error information?
I've never seen your syntax before, putting an exists clause before the insert clause, but the following should work.
INSERT INTO `friends`
SELECT :id, :fp_id, :name, :id2, :fb_id2, :name2
FROM `friends`
WHERE NOT EXISTS ( select `id` from friends where `id` = :id )
LIMIT 1;
Just realized that you'll need at least one record in your friends table before this'll go.
insert IGNORE into `friends` (`id`, `fb_id`, `name`, `id2`, `fb_id2`, `name2`)
values (:id, :fb_id, :name, :id2, :fb_id2, :name2)
Or you want to prevent duplicate id's you can add a trigger
DELIMITER $$
CREATE TRIGGER bi_friends_each BEFORE INSERT ON friends FOR EACH ROW
BEGIN
DECLARE TestId integer;
SELECT id INTO TestId FROM friends WHERE id = new.id LIMIT 1;
IF (id IS NOT NULL) THEN BEGIN
/*force an error to prevent insert*/
SELECT * FROM force_an_error_table_unwilling_to_insert_dup_key;
END; END IF;
END $$
DELIMITER ;
Note that if id is a UNIQUE or PRIMARY KEY field inserting a duplicate key will create an error and rollback any pending transaction.
If you are using a non-transactional engine, MySQL will stop inserting rows at the error point leaving only part of your rows inserted.
Your question is vague as to why you want to do the IGNORE test. So I'll recap the options and the implications:
If you want a transaction to fail, set id as primary key and just insert as normal, the resulting conflict will generate an error and rollback the transaction.
If you want to just insert stuff with no worries about duplicate id's set field is to AUTOINCREMENT and replace the value for id with null. INSERT INTO table (id, fb_id,name,id,fb_id2,name2) VALUES (null,:fb_id,:name,:id2,:fb_id2,:name2)
If you just want the one insert not to succeed, do the INSERT IGNORE ... as stated above.
If you do not have transactions (MyISAM et al), you may have to do a test SELECT first and only INSERT a bunch of values after the test shows it is save to proceed.
You could use INSERT IGNORE assuming you have a unique index on id. See this post for discussion about the pros/cons: "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
This solution works even if you do not have any rows in your table.
INSERT INTO t (
x,
y,
z) (
SELECT
'00000',
'11111',
'22222'
FROM
DUAL
WHERE
NOT EXISTS (
SELECT
1
FROM
t
WHERE
c = '00000'
AND x = '11111'
AND y = '22222'
)
LIMIT 1
);