How to write MySQL query for If Exists Update Else Insert? - mysql

I tried to write MySQL Insert and update query in one query but seems it not working can someone please explain me what is the error of following code, thank you..
IF EXISTS
(
SELECT *
FROM contact
WHERE account_id='".$_GET['acc']."' AND contact_id='".$_GET['con']."'
)
UPDATE contact SET
category='".$_GET['cat']."', shares='".$_GET['sh']."'
WHERE account_id='".$_GET['acc']."' AND contact_id='".$_GET['con']."'
ELSE
INSERT INTO contact
(account_id,contact_id, category, shares)
VALUES ('".$_GET['acc']."', '".$_GET['con']."', '".$_GET['cat']."', '".$_GET['sh']."')

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
See REPLACE syntax

Related

Insert a record only if it is not present

I need to create a query to insert some records, the record must be unique. If it exists I need the recorded ID else if it doesnt exist I want insert it and get the new ID. I wrote that query but it doesnt work.
SELECT id FROM tags WHERE slug = 'category_x'
WHERE NO EXISTS (INSERT INTO tags('name', 'slug') VALUES('Category X','category_x'));
It's called UPSERT (i.e. UPdate or inSERT).
INSERT INTO tags
('name', 'slug')
VALUES('Category X','category_x')
ON DUPLICATE KEY UPDATE
'slug' = 'category_x'
MySql Reference: 13.2.5.3. INSERT ... ON DUPLICATE KEY UPDATE Syntax
Try something like...
IF (NOT EXISTS (SELECT id FROM tags WHERE slug = 'category_x'))
BEGIN
INSERT INTO tags('name', 'slug') VALUES('Category X','category_x');
END
ELSE
BEGIN
SELECT id FROM tags WHERE slug = 'category_x'
END
But you can leave the ELSE part and SELECT the id, this way the query will always return the id, irrespective of the insert...
MySQL has nice REPLACE. It is easy to use and remember it's syntax as same as INSERT.
in you case, just run following query.
REPLACE INTO tags('name', 'slug') VALUES('Category X','category_x')
It acts like INSERT when no unique constraint violation. If duplicated value found on PK or UNIQUE key, then other columns will be UPDATED with given values. It is done by DELETE duplicated record and INSERT new record.

INSERT ... ON DUPLICATE KEY UPDATE how can I tell which records updated and which inserted

In a PHP script I'm using the MySQL INSERT ... ON DUPLICATE KEY UPDATE command to insert/update a number of records in my DB.
Is there anything that MySQL returns to say which records were inserted or updated?
An 'ugly' way would be to do a SELECT before each INSERT and see if the key exists before each INSERT but I'd like to know if MySQL has this function built in.
In case anyone need further info on what I'm trying to do is, to save the record id's to a log.
You will need another SELECT regardless, specifically SELECT ROW_COUNT().
From http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
For INSERT ... ON DUPLICATE KEY UPDATE statements, the affected-rows value is 1 if the row is inserted as a new row and 2 if an existing row is updated.
No, there is no way to tell which records were inserted and which were updated purely with the means provided by MySQL without additional queries. However, you can add a column to the table where you can keep an indicator that you can use to mark the record as updated instead of inserted, e.g.
INSERT INTO YourTable (Col1, Col2, Updated)
VALUES ("value1", "value2", 0)
ON DUPLICATE KEY UPDATE
Col1 = values(Col1),
Col2 = values(Col2),
Updated = 1

Web SQL - Insert if not exists or Unique column?

I try to execute insert or ignore into WDCategory(name,userID) values('Cate 1',1) which name is a unique column but not successful if there is a record with same name in the table. "Not Successful" means that the query fail instead of execute and insert nothing. I have try insert into WDCategory(name,userID) values('Cate 1',1) If Not Exists but nothing change.
Update: I try
insert or replace into WDCategory(name,userID) values('Cate 1',1)
it works. But the record now have a new id (auto increase). Is there any way to keep the old values?
Please help!

how to insert without duplicate from one table into another

I tried to insert from one table into another and im having with the redundancy..
I came up with a query but every time when i execute it, It cannot deals with duplicate.
here's my query...
INSERT INTO balik ( balik_date, balik_time, balik_cardID, balik_status,balik_type)
select current_date(), '00:00:00', L_CardID, 'BELUM BALIK', L_Type
FROM logdetail t1
LEFT JOIN balik t2 ON (t1.L_CardID = t2.balik_cardID)
WHERE t1.L_Type = 'IN'
any help will be greatly appreciated
Use INSERT IGNORE instant of INSERT.
Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an
existing record, MySQL inserts it as usual. If the record is a
duplicate, the IGNORE keyword tells MySQL to discard it silently
without generating an error.
OR
Check row count for unique field. If row exist don't insert or update.
OR
Use REPLACE rather than INSERT. If the record is new, it's inserted
just as with INSERT. If it's a duplicate, the new record replaces the
old one:
Source for definitions MySQL Handling Duplicates

insert - where not exists

I would like to insert a record into a table if a record doesnt exist already exist with that domain name. The following SQL should achieve this but is getting an error.
The reason I want to do the update first is because I am doing multiple updates later in my code and need the record in my table first before doing all of the updates.
Why am I getting an error on this mySQL query?
insert into domain (name)
values ('domain.com.au')
WHERE NOT EXISTS
(
select name
from domain
where name = 'domain.com.au'
);
Both queries when split work fine but when together do not.
Let your database handle it for you. Use a unique index on name and your INSERT will fail if you try to insert a duplicate.
CREATE UNIQUE INDEX idx_name ON domain (name)
You cannot combine WHERE with INSERT clause. Use REPLACE INTO instead.
What error are you getting?
My guess would be the that the select inside the 'where not exists' is not allowed.